开发者

How to insert selected rows value of Gridview into Database in .net

I am Developing Windows Fo开发者_Go百科rm Application in .Net, I want to insert selected rows value of Gridview into database. First Column of my GridView is Checkbox, when user check one or more checkbox from gridview, i want to insert values of respective rows into Database.

In Web application i done this using DataKeyNames property of GridView. Want to know how to do it in Windows Form Application. I am using Visual Studio 2005.


I answer to a question that is very close to your question, maybe it help you:

How to add gridview rows to a datatable?

your answer for selecting rows:

    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;
                }
    }


Still not sure what you're looking for but the following might help at least.

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 gets out the values from the row and uses those values as the SqlParameters to an insert statement and then you execute the insert as shown in:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx

Assuming you're using SQL Server, otherwise you'd need other classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜