user3568531
user3568531

Reputation: 21

Retrieve and store checkbox value in database when selected from gridview in asp.net c#?

I have a GridView containing a CheckBox, displaying student attendance information. When I check the CheckBox, the value (which is a bit value) does not get stored in the database.

Here is my code:

protected void btn_attendence_Click(object sender, EventArgs e)
{
    con = [CONNECTION STRING];
    cn = new SqlConnection(con);
    cn.Open();
    foreach (GridViewRow gvrow in grid_attendence.Rows)
    {
        CheckBox chk = ((CheckBox)grid_attendence.FindControl("chbox") as CheckBox);
        if (chk.Checked)
        {
            st = "insert into atd(attend,stno,stname) values ('" + gvrow.Cells[0].Text + "','" + gvrow.Cells[1].Text + "','" + gvrow.Cells[2].Text + "')";

            cmd = new SqlCommand(st, cn);
            cmd.ExecuteNonQuery();
            Response.Write("Record inserted");
            cn.Close();
        }
    }
}

Upvotes: 2

Views: 3967

Answers (2)

Amnesh Goel
Amnesh Goel

Reputation: 2655

--Add one more column to your table status boolean type and set its value to 0 or 1.

CheckBox chk = ((CheckBox)grid_attendence.FindControl("chbox") as CheckBox);
if (chk.Checked)
{
    st = "insert into atd(attend,stno,stname,status) values ('" + gvrow.Cells[0].Text + "','" + gvrow.Cells[1].Text + "','" + gvrow.Cells[2].Text + "',1)";
}
else
{
    st = "insert into atd(attend,stno,stname,status) values ('" + gvrow.Cells[0].Text + "','" + gvrow.Cells[1].Text + "','" + gvrow.Cells[2].Text + "',0)";
}
cmd = new SqlCommand(st, cn);
cmd.ExecuteNonQuery();
Response.Write("Record inserted");
cn.Close();

Upvotes: 1

Claudio Redi
Claudio Redi

Reputation: 68440

Change (CheckBox)grid_attendence by (CheckBox)gvrow

foreach (GridViewRow gvrow in grid_attendence.Rows)
{
    var chk = (CheckBox)gvrow.FindControl("chbox");
    if (chk.Checked)
    {
        st = "insert into atd(attend,stno,stname) values ('" + gvrow.Cells[0].Text + "','" + gvrow.Cells[1].Text + "','" + gvrow.Cells[2].Text + "')";

        cmd = new SqlCommand(st, cn);
        cmd.ExecuteNonQuery();
        Response.Write("Record inserted");
        cn.Close();

    }
}

Some extra things:

  • You shouldn't be creating the query like using string concatenation, you're exposed to sql injection attack. Use parametrized query instead.

  • No need to double cast like this ((CheckBox)grid_attendence.FindControl("chbox") as CheckBox) (take a look to my code)

Upvotes: 3

Related Questions