[英]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.