首页 文章

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

提问于
浏览
35

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

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

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

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

先感谢您 .

8 回答

  • 12

    您可以尝试使用此代码 - 基于 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

    我发现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;
    }
    
  • 52

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

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

    //为行的列赋值(此行应该有28列):

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

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

    table.Rows.Add(row);
    
  • 3

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

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

    这对我有用:

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

    for 语句后尝试 table.Rows.add(row); .

  • 0
    GRV.DataSource = Class1.DataTable;
                GRV.DataBind();
    
    Class1.GRV.Rows[e.RowIndex].Delete();
            GRV.DataSource = Class1.DataTable;
            GRV.DataBind();
    

相关问题