wormwood
wormwood

Reputation: 441

selecting individual rows from gridview using check box

I have a gridview that contains a check box inside the template field. I want to retrieve the values of the rows where the check box is checked so I can update them through the database. Here's my code:

    protected void approve_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            if (((CheckBox)GridView1.Rows[i].FindControl("Select")).Checked) 
            {

//I thought if the loop finds a checked check box, it will execute the following to that row:

                con.Open();

                string approve = "update table set status ='Approved' where ID=" + GridView1.Rows[i].Cells[1].Text + "";

                SqlCommand scmapprove = new SqlCommand(approve, con);

                scmapprove.ExecuteNonQuery();

                view();

                con.Close();

            }

                            }

However, it doesn't seem to work. For example I checked five rows from the table, It only updates the first row. What should I do?

Upvotes: 1

Views: 2227

Answers (1)

afzalulh
afzalulh

Reputation: 7943

You are rebinding the Gridview after finding a checked row. Bind it after completing all update operations:

protected void approve_Click(object sender, EventArgs e)
{
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        if (((CheckBox)GridView1.Rows[i].FindControl("Select")).Checked) 
        {
            //I thought if the loop finds a checked check box, it will execute the following to that row:
            con.Open();
            string approve = "update table set status ='Approved' where ID=" + GridView1.Rows[i].Cells[1].Text + "";

            SqlCommand scmapprove = new SqlCommand(approve, con);
            scmapprove.ExecuteNonQuery();

            //view(); //Donot rebind the gridview now.
            con.Close();
        }
    }

    view();
}

Upvotes: 2

Related Questions