如何动态地向DataGridview添加数据? [英] how to add data dynamically to DataGridview?
本文介绍了如何动态地向DataGridview添加数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想动态地将数据添加到 DataGridView
并编写此代码。
I want to add data dynamically to DataGridView
and I write this code.
private void btnsubmit_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("pname".ToString());
table.Columns.Add("pprice".ToString());
table.Columns.Add("pq".ToString());
DataRow dr = table.NewRow();
dr["pname"] = cmbpname.Text;
dr["pprice"] = txtpprice.Text;
dr["pq"] = txtpqu.Text;
table.Rows.Add(dr);
var bindingSource = new BindingSource();
bindingSource.DataSource = table;
dataGridView1.DataSource = bindingSource;
bindingSource.ResetBindings(true);
}
但是每当我点击提交按钮时,前一个值都会被删除并插入新值,但我想要输入所有值而不会丢失先前的值。建议解决我的问题的一些解决方案谢谢:)
But whenever I click on submit button previous value get removed and new value inserted but I want to enter all value without losing previous value. Suggest some solution to solve my problem thanks :)
推荐答案
在每个按钮上单击,您将创建一个新的DataTable
将其绑定到DataGridView
。相反,检查网格是否已存在数据源,如果是,则向其添加新行。
On each button click, you are creating a newDataTable
to bind it to theDataGridView
. Instead, check if a datasource already exists for the grid and if yes, add a new row to it.
您好,
出现问题的原因是每按一次按钮,新的DataTable
就会创建,因此所有以前的数据都会永久删除。我建议你在submitbutton_click事件之外声明并定义DataTable
。并将DataTable
设为static
。
谢谢
animesh
Hello ,
The problem occurs because for every button click , a newlyDataTable
creates and hence all the previous data removes permanently . I suggest you to declare and define theDataTable
outside of submitbutton_click event . and make theDataTable
asstatic
.
thanks
animesh
您必须在现有数据表中添加新行,而不是创建每增加一个新行,请检查一下:
在ASP.Net-GridView-Control-with-TextBoxes.aspx中添加动态行 - [^ ]
You have to add new row to the existing datatable, not creating new one at every add new row, check this out:
Adding-Dynamic-Rows-in-ASP.Net-GridView-Control-with-TextBoxes.aspx[^]
这篇关于如何动态地向DataGridview添加数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文