How to insert selected value of Gridview rows into database in .net
I am developing a Windows Form Application in .Net, I want to insert selected Gridview row values into a database. The first column of my GridView is a checkbox, when the user checks one or more checkboxes from the gridview, I want to insert the values of the corresponding rows into the database.
In a web application, I did this using the DataKeyNames property of the GridView. Wondering how to do this in a Windows Form application. I am using Visual Studio 2005.
a source to share
I am answering a question that is very close to your question, maybe this will help you:
How can I add gridview rows to datatable?
answer for row selection:
for (int i = 0; i < grdList.Rows.Count; i++)
{
string key = grdList.DataKeys[i].Value.ToString();
if (((CheckBox)grdList.Rows[i].FindControl("chkSelect")).Checked)
foreach (TargetObject obj in objects)
if (obj.Key == key)
{
//do something like below
flag = true;
break;
}
}
a source to share
Still not sure what you are looking for, but at least the following might help.
foreach(DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells[0];
if(cell.Value)
{
InsertRow(row);
}
}
The code assumes that the first column is of type DataGridViewCheckBoxCell.
Where InsertRow fetches values from the row and uses those values as SqlParameters for the insert statement, and then you insert the insert as shown in the picture:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
Assuming you are using SQL Server, otherwise you will need other classes.
a source to share