Add row datagridview at every button click

為{幸葍}努か 提交于 2020-01-03 03:09:06

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/16054612/add-row-datagridview-at-every-button-click

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