我有一个包含CheckBox的GridView,显示学生的出勤信息。当我检查CheckBox时,值(这是一个位值)不会存储在数据库中。
这是我的代码:
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();
}
}
}
答案 0 :(得分:3)
按(CheckBox)grid_attendence
(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();
}
}
一些额外的事情:
您不应该像使用字符串连接一样创建查询,而是会受到sql injection
攻击。改为使用参数化查询。
无需像这样((CheckBox)grid_attendence.FindControl("chbox") as CheckBox)
进行双重演绎(请查看我的代码)
答案 1 :(得分:1)
- 在表状态布尔类型中再添加一列,并将其值设置为0或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();