How to add new DataRow into DataTable?

北城以北 提交于 2019-12-31 10:19:34

问题


I have a DataGridView binded to a DataTable (DataTable binded to database). I need to add a DataRow to the DataTable. I'm trying to use the following code:

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

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

But it doesn't work, DataGridView has never been added a new row. Please, tell me, how can I fix my code?

Thank you in advance.


回答1:


You can try with this code - based on Rows.Add method

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

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




回答2:


I found dotnetperls examples on DataRow very helpful. Code snippet for new DataTable from there:

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



回答3:


//َCreating a new row with the structure of the table:

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

//Giving values to the columns of the row(this row is supposed to have 28 columns):

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



回答4:


You have to add the row explicitly to the table

table.Rows.Add(row);



回答5:


If need to copy from another table then need to copy structure first:

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



回答6:


This works for me:

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



回答7:


try table.Rows.add(row); after your for statement.




回答8:


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

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


来源:https://stackoverflow.com/questions/12642049/how-to-add-new-datarow-into-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!