views:

457

answers:

2

I am Developing Windows Form 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.

+1  A: 

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.

ho1
@ho, Can i solve my problem using this?
MAS1
I think my first answer was wrong, I've amended it now to something that hopefully helps.
ho1
@ho, i am not using listView
MAS1
Sorry about that, bit confused today it seems. Though the idea is the same.
ho1
@ho, thanx for your post.
MAS1
+1  A: 

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;
                }
    }
masoud ramezani
@masoud, thanx. But in that case OP uses SqlBulkCopy. Can i do it without using SqlBulkCopy. And OP inserted all rows, i want to insert only selected rows data of GriedView.
MAS1
@MAS1: yes, you can change the code for selecting your favorite rows. you can use Enterprise Library if you can't use SqlBulkCopy.
masoud ramezani
@masoud,that only i want to know, how to check,which check boxes are checked by user.
MAS1
@MAS1: you can put a checkbox on the first column then check it. please see the updated answer.
masoud ramezani
@masoud, thanx.
MAS1