Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to add data dynamically to DataGridView and I write this code.

C#
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 :)
Posted
Updated 26-Feb-14 20:41pm
v2

On each button click, you are creating a new DataTable to bind it to the DataGridView. Instead, check if a datasource already exists for the grid and if yes, add a new row to it.
 
Share this answer
 
Hello ,

The problem occurs because for every button click , a newly DataTable creates and hence all the previous data removes permanently . I suggest you to declare and define the DataTable outside of submitbutton_click event . and make the DataTable as static .

thanks
animesh
 
Share this answer
 
v2
Comments
varuncodee 27-Feb-14 3:08am    
thank you sir,
could you please give me a example?
Animesh Datta 27-Feb-14 3:29am    
first declare the DataTable globally like this
static DataTable dt=new DataTable();

next define its columns in Form_Load
dt.Columns.Add("pname");
dt.Columns.Add("pprice");

now add row in button_click

DataRow dr = dt.NewRow();
dr["pname"] = cmbpname.Text;
dr["pprice"] = txtpprice.Text;
dt.Rows.Add(dr);
Datagridview1.DataSource=dt;

thanks
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[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900