1

I have on a usercontrol a datagridview. I created a datatable and I set the source of datagrid to be this datatable. I want,at runtime,to be able to add how many rows on gridview I want at every button click.

My code :

 private DataTable CreateTable()
    {
        Datatable table=new Datatable();
        table.Columns.Add("Name".ToString());
        table.Columns.Add("Size".ToString());
        DataRow dr = table.NewRow();
        dr["Name"] = "Mike";
        DataRow dr2 = table.NewRow();
        dr2["Name"] = "Ryan;
        DataRow dr3 = table.NewRow();
        dr3["Name"] = "Taylor";
        dr["Size"] = " one";
        dr2["Size"] = "two";
        table.Rows.Add(dr);
        table.Rows.Add(dr2);
        table.Rows.Add(dr3);
        return table;
     //and on my constructor I set gridview.DataSource=Datatable;
    }

 //Code  on the event:
 private void button_Click(object sender, EventArgs e)
    {

        DataRow NewRow = table.NewRow();
        table.Rows.Add(NewRow);
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Viva
  • 1,983
  • 5
  • 26
  • 38

2 Answers2

3

You need to define the DataTable at form level. Then in button click you can do:

private void button_Click(object sender, EventArgs e)
{
    DataRow NewRow = table.NewRow();
    table.Rows.Add(NewRow);
    gridview.DataSource=table; //specify the source
}

For defining table at form level:

DataTable table; //DataTable at form level

private DataTable CreateTable()
{
    table=new Datatable(); //here insntianting the form level table. 
    table.Columns.Add("Name".ToString());
    table.Columns.Add("Size".ToString());
    DataRow dr = table.NewRow();
    dr["Name"] = "Mike";
    DataRow dr2 = table.NewRow();
    dr2["Name"] = "Ryan;
    DataRow dr3 = table.NewRow();
    dr3["Name"] = "Taylor";
    dr["Size"] = " one";
    dr2["Size"] = "two";
    table.Rows.Add(dr);
    table.Rows.Add(dr2);
    table.Rows.Add(dr3);
    return table;
 //and on my constructor I set gridview.DataSource=Datatable;
}
Habib
  • 219,104
  • 29
  • 407
  • 436
1

I would recommend the following approach for better handling.

Create generic list, for every click append the list with the new set of data, then convert the list to DataTable as said in the below link, then bind DataTable to the grid.

Convert generic List/Enumerable to DataTable?

If you want sample code please let me know.

Community
  • 1
  • 1
Dev
  • 960
  • 2
  • 15
  • 35