if there are 3-4 textboxes diplaying some calcuted value,then how can we add these values to datagrid view and database
Insert dat to datagrid view from twxt boxes
Collapse
X
-
you can add textbox values to a datagridview by just
1)create a "DataTable"
2)create a DataColumn
3)Add DataColumn to DataTable
4)create a new DataRow
5)Append textBox value to DataRow
6)Add DataRow to DataTable
7)set datasource of datagridview to DataTable
sample code.....
1)DataTable dt = new DataTable();
2)DataColumn values = new DataColumn("val ues",typeof(Sys tem.String));
3)dt.Columns.Ad d(values);
4)DataRow dr = dt.NewRow();
5)dr["values"] = textBox1.Text;
6)dt.Rows.Add(d r);
7)dataGridView1 .DataSource = dt; -
if you understand the above code you can figure out the answer yourself....... ......
if you want to add the next value to a new row of dagaGridView , just create a new datarow as shown before
/*
dr = dt.NewRow();
dt["columnName "] = "the string you want to insert";
dt.Rows.Add(dr) ;
*/ this code will add a new row to your dataGridView
with the given string.
in order to add new values to your dataGridView you have to code in such a way that the above code executes each time you want to insert a string.....Comment
-
... in case if you want to add your values to new columns the just create new columns
values = new DataColumn("val ues1",typeof(Sy stem.String));
dt.Columns.Add( values);
values = new DataColumn("val ues2",typeof(Sy stem.String));
dt.Columns.Add( values);
and now create row like
string[] row = {""+textBox1.Te xt,""+textBox2. Text}
dt.Rows.Add(row );
for more values add more columns and then add values in
string[] row = {""+textBox1.Te xt,""+textBox2. Text+,.....}Comment
-
Given two textboxs (textbox1 and textbox2), you can add it content to datagridview:
Obviously you had to have the two columns added in the datagridview control. Then to save it to database (I'll omit connections and queries):Code:dt.Rows.Add(textbox1.Text, textbox2.Text);
Code:SqlCommand command = new SqlCommand(); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { command.CommandText = "INSERT INTO table(val1,val2) VALUES(@val1,@val2)"; command.Parameters.AddWithValue("@val1", dt.Rows[i].Cells[0].Value.ToString()); command.Parameters.AddWithValue("@val2", dt.Rows[i].Cells[1].Value.ToString()); command.ExecuteNonQuery(); } }Comment
Comment