gpt4 book ai didi

c# - 在每次单击按钮时添加行数据 GridView

转载 作者:太空宇宙 更新时间:2023-11-03 21:47:48 24 4
gpt4 key购买 nike

我在 usercontrol 上有一个 datagridview。我创建了一个数据表,并将数据网格的源设置为此数据表。我希望在运行时能够在每次单击按钮时在 gridview 上添加我想要的行数。

我的代码:

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

最佳答案

您需要在表单级别定义DataTable。然后在按钮点击你可以做:

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

在表单级别定义表格:

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

关于c# - 在每次单击按钮时添加行数据 GridView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16054612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com