如何在WinForms中的DataGridView中添加行?

5

我想在datagridview中添加行。我尝试了很多可能性,但是它上面没有显示任何内容。我认为最好的解决方案是创建一个datatable,然后将其用作我的gridview的数据源。我使用winforms。欢迎提出任何其他想法。到目前为止,这是我尝试过的:

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;
}

1
我很少做WinForms,但是如果你要分配一个DataSource,难道你不也必须绑定它吗? - Tim
2
我认为在WinForms上你不必绑定它。谢谢。 - Viva
1
目的是什么?您是否在DataGridView中定义了任何列?添加行就像使用“gridview.Rows.Add(n)”添加n行或“gridview.Rows.Add()”一样简单。 - V4Vendetta
1
正在从数据库中获取数据以供“GridView”使用。 - Arshad
4个回答

11

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

  1. dr["Color "] = "blue";列名 Color 不应该有空格 dr["Color"] = "blue";
  2. 你忘记向表中添加行了

    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();
}

3

有不同的方法,但要根据不同的情况选择。

如下面的代码所示,在使用字符串数组时,可以使用GridView的add方法:

datagridview1.Rows.Add( { val, val, val });

这取决于您想要应用它的上下文和情境。

在IT技术中,这句话的意思是根据具体情况来确定使用方法。

3

尝试这种方法:

dataGridView1.Columns.Add("Col1", "Name"); // "Col1" is the name of the column and  "Name" is the column header text"
dataGridView1.Columns.Add("Col2", "Age");
dataGridView1.Rows.Add("ABC", "25");

希望这能帮到您:)

2
DataGridView dgv = new DataGridView();

DataTable table = new DataTable();

dgv.DataSource = table;

table.Columns.Add("Name");
table.Columns.Add("Color");
table.Rows.Add("Mike", "blue");
table.Rows.Add("Pat", "yellow");

this.Controls.Add(dgv);

非常感谢!但是,我的网格视图上似乎什么也没有显示出来。我无法解释为什么... - Viva

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接