Click here to Skip to main content
15,895,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a Form which is calculating and displaying data in TexBoxes which I'm using for further calculation, now on Save Button Click I have this written code:
C#
DataTable dt = new DataTable();
DataRow drow  = dt.NewRow();
DataColumn dc = new DataColumn("X", typeof(System.String));
DataColumn dc1 = new DataColumn("Y", typeof(System.String));
DataColumn dc2 = new DataColumn("Z", typeof(System.String));
dt.Columns.Add(dc);
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
string[] rows = { "" + textBox10.Text, "" + textBox11.Text, "" + textBox12.Text };
dt.Rows.Add(rows);
dataGridView1.DataSource = dt;

It is working fine except that I want on save each time value gets saved to new row without overwriting the previous like:
r1 11 111 111
r2 22 11 1111
...
etc
Posted
Updated 26-Jul-10 3:57am
v3

For that you have to "create new row on same table" on each save click.
Here, you are creating new table on every click, new table will always have only 1 record.
Create table only once and then add rows to it on every click. :)
 
Share this answer
 
Hi,

I think you had written whole code inside Save button click, you should have to define code on following manner

1. define this variable gollbally


DataTable dt;

2. in form_Load event

dt = new DataTable();<br/>
DataColumn dc = new DataColumn("X", typeof(System.String));

DataColumn dc1 = new DataColumn("Y", typeof(System.String));

DataColumn dc2 = new DataColumn("Z", typeof(System.String));

dt.Columns.Add(dc);

dt.Columns.Add(dc1);

dt.Columns.Add(dc2);

3. in Save button click

DataRow drow = dt.NewRow();

C#
string[] rows = { "" + textBox10.Text, "" + textBox11.Text, "" + textBox12.Text };
dt.Rows.Add(rows);

BindGrd();
4. BindGrid()

public void dataGridView1.DataSource = dt;
 
Share this answer
 
Comments
shweta134 26-Jul-10 6:13am    
"Object reference not set to an instance of an object."
I'm getting tis error on
DataRow drow = dt.NewRow();
koool.kabeer 26-Jul-10 8:09am    
you may have forgot to initialize the DataTable in you Save button click event handler
William Winner 2-Aug-10 13:58pm    
you should bind the DataGridView in the FormLoad after the DataTable was created and not every time you add a new row. It's just an unnecessary step.

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