如何将新的DataRow添加到DataTable中?

时间:2012-09-28 14:32:17

标签: c# datagridview datatable datarow

我有DataGridView绑定到DataTable(绑定到数据库的DataTable)。我需要向DataRow添加DataTable。我正在尝试使用以下代码:

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

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

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

提前谢谢你。

8 个答案:

答案 0 :(得分:53)

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

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

链接:https://msdn.microsoft.com/en-us/library/9yfsd47w.aspx

答案 1 :(得分:13)

我发现dotnetperls examples on 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;
}

答案 2 :(得分: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();
}

答案 3 :(得分:3)

您必须add the row明确指向表格

table.Rows.Add(row);

答案 4 :(得分:2)

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

DataTable copyDt = existentDt.Clone();
copyDt.ImportRow(existentDt.Rows[0]);

答案 5 :(得分:1)

这对我有用:

var table = new DataTable();
table.Rows.Add();

答案 6 :(得分:0)

table.Rows.add(row);声明之后尝试for

答案 7 :(得分:-1)

    GRV.DataSource = Class1.DataTable;
            GRV.DataBind();

Class1.GRV.Rows[e.RowIndex].Delete();
        GRV.DataSource = Class1.DataTable;
        GRV.DataBind();
相关问题