CheckBox的CheckedChanged事件获取所在GridView中的Cell值

在开发的一个网站的后台中,用到这么一个功能:

    1)在GridView中绑定一个CheckBox;

    2)当选中/取消选中CheckBox时,激发后台表中对应数据操作或者设置对应标志;

  在 protected void CheckBox1_CheckedChanged(object sender, EventArgs e){} 中,通过获取sender的parent来进行操作,代码为:

   

代码
 1             CheckBox chk = (CheckBox)sender;
 2             DataControlFieldCell dcf = (DataControlFieldCell)chk.Parent;
 3             GridViewRow gvr = (GridViewRow)dcf.Parent;
 4             try
 5             {
 6                 if (chk.Checked)
 7                 {
 8                     model.NewsId = NewsID;//model为映射表的实例化对象
 9                     model.AddressId = int.Parse(gvr.Cells[1].Text);//此处宏来获取GridView中的某一个Cell的值;
10                     model.Status = 1;
11                     model.Memo = "";
12                     bll.Add(model); //执行一个添加操作.
13                 }
14                 else
15                 {
16                     strsql = "delete from biao1 where NewsId=" + NewsID + " and AddressId=" + int.Parse(gvr.Cells[1].Text);
17                     DbHelper.ExecuteSql(strsql);
18                 }
19             }
20             catch (Exception ex)
21             {
22                 //throw(this, ex.ToString());
23             }

 

   附带:

        如果要遍历GridView中的CheckBox是否选中,并做相应操作,则:

   

代码
 1             for (int j = 0; j < GridView1.Rows.Count; j++)
 2             {
 3                 CheckBox chbox = GridView1.Rows[j].FindControl("CheckBox1"as CheckBox;
 4                 if (chbox.Checked)
 5                 {
 6                     model.NewsId = NewsID;//
 7                     model.AddressId = int.Parse(GridView1.Rows[j].Cells[1].Text);
 8                     model.Status = 1;
 9                     model.Memo = "";
10                     bll.Add(model);
11                 }
12             }

 

 

 

posted @ 2010-04-12 23:28  荣景智工  阅读(1770)  评论(0编辑  收藏  举报