[英]Retrieve and store checkbox value in database when selected from gridview in asp.net c#?
我有一个包含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();
}
}
}
通过(CheckBox)gvrow
更改(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)
进行双重((CheckBox)grid_attendence.FindControl("chbox") as CheckBox)
看看我的代码)
-将另一列添加到表状态布尔类型并将其值设置为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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.