views:

1721

answers:

2

I have a datagrid that has two columns. The DataSource for the datagrid is "myTable" which is a DataTable. All I am trying to do is add a row to the DataTable and have the new row be displayed in the datagrid. Here is the simple code I wrote to add the item to the DataTable:

DataRow dRow = myTable.NewRow();
dRow.ItemArray.SetValue("test", 0);
dRow.ItemArray.SetValue("test1", 1);

What am I missing to make the new data row show in the datagrid?

Thanks!

+5  A: 

The .NewRow() method doesn't add the row to the table, it only returns a row with the appropriate fields included in it. You still need to add the row to the table.

myTable.Rows.Add(dRow);
Soviut
+2  A: 

The following works without any issues - adding a row to the table is the step you were missing.

        DataTable dt = new DataTable();
        private void Form1_Load(object sender, EventArgs e)
        {
            dt.Columns.Add("a");
            dt.Columns.Add("b");
            dt.Rows.Add("aaa", "bbb");
            dataGrid1.DataSource = dt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dt.Rows.Add("111", "222");
        }
Ilya Tchivilev