42

我有一个DataGridView绑定到一个DataTableDataTable绑定到数据库)。我需要DataRowDataTable. 我正在尝试使用以下代码:

dataGridViewPersons.BindingContext[table].EndCurrentEdit();
DataRow row = table.NewRow();

for (int i = 0; i < 28; i++)
{
    row[i] = i.ToString();
}

但它不起作用,DataGridView从未添加过新行。请告诉我,我该如何修复我的代码?

先感谢您。

4

8 回答 8

66

您可以尝试使用此代码 - 基于Rows.Add method

DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);

参考:https ://docs.microsoft.com/dotnet/api/system.data.datarowcollection.add?view=net-5.0#System_Data_DataRowCollection_Add_System_Data_DataRow _

于 2012-09-28T14:34:44.653 回答
28

我发现dotnetperls 的例子DataRow很有帮助。DataTable来自那里的新代码片段:

static DataTable GetTable()
{
    // Here we create a DataTable with four columns.
    DataTable table = new DataTable();
    table.Columns.Add("Weight", typeof(int));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Breed", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    // Here we add five DataRows.
    table.Rows.Add(57, "Koko", "Shar Pei", DateTime.Now);
    table.Rows.Add(130, "Fido", "Bullmastiff", DateTime.Now);
    table.Rows.Add(92, "Alex", "Anatolian Shepherd Dog", DateTime.Now);
    table.Rows.Add(25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now);
    table.Rows.Add(7, "Candy", "Yorkshire Terrier", DateTime.Now);

    return table;
}
于 2016-11-18T15:50:46.310 回答
10

//َ用表的结构创建一个新行:

DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);

//给行的列赋值(这一行应该有28列):

for (int i = 0; i < 28; i++)
{
    row[i] = i.ToString();
}
于 2013-11-14T05:55:05.203 回答
3

您必须将该行显式添加到表中

table.Rows.Add(row);
于 2012-09-28T14:35:34.733 回答
2

如果需要从另一个表中复制,则需要先复制结构:

DataTable copyDt = existentDt.Clone();
copyDt.ImportRow(existentDt.Rows[0]);
于 2013-03-14T21:54:36.750 回答
1

这对我有用:

var table = new DataTable();
table.Rows.Add();
于 2012-09-28T14:55:24.893 回答
0

table.Rows.add(row);在你的for陈述之后尝试。

于 2012-09-28T14:36:07.977 回答
-2
    GRV.DataSource = Class1.DataTable;
            GRV.DataBind();

Class1.GRV.Rows[e.RowIndex].Delete();
        GRV.DataSource = Class1.DataTable;
        GRV.DataBind();
于 2017-06-20T19:22:07.997 回答