本文介绍了如何将行添加到 datagridview winforms?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向 datagridview 添加行.我尝试了很多可能性,但它没有出现任何内容.我认为最好的解决方案是创建一个数据表,然后将其用作我的 gridview 的数据源.我使用winforms.请,欢迎任何其他想法.这是我迄今为止尝试过的:

I want to add rows to a datagridview. I tried a lot of possibilities, but it doesn't appear anything on it. I think the best solution is to create a datatable, and then to use it as datasource for my gridview. I use winforms. Please, any other idea is welcomed . This is what I have tried so far:

public DataTable GetResultsTable()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Name".ToString());
        table.Columns.Add("Color".ToString());
        DataRow dr;
        dr = table.NewRow();
        dr["Name"] = "Mike";
        dr["Color "] = "blue";
        table.AcceptChanges();
        return table;
    }
public void gridview()
{
     datagridview1.DataSource=null;
     datagridview1.DataSource=table;
}

推荐答案

我发现你的代码中有两个错误:

i found two mistake in your code:

  1. dr["Color "] = "blue"; Column Color 不能有空格 dr["Color"] = "blue";
  2. 您忘记在表格中添加行

  1. dr["Color "] = "blue"; Column Color should without space dr["Color"] = "blue";
  2. You forgot to add row to the table

table.Rows.Add(dr);

你可以试试这个

public DataTable GetResultsTable()
{
    DataTable table = new DataTable();
    table.Columns.Add("Name".ToString());
    table.Columns.Add("Color".ToString());
    DataRow dr = table.NewRow();
    dr["Name"] = "Mike";
    dr["Color"] = "blue";
    table.Rows.Add(dr);
    return table;
}
public void gridview()
{
    datagridview1.DataSource =  GetResultsTable();
}

这篇关于如何将行添加到 datagridview winforms?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 03:48