选择DataList中的CheckBox控件后该行背景变色

来源:互联网 发布:origin软件的使用方法 编辑:程序博客网 时间:2024/05/20 07:33

闲时看了一篇“选择DataGrid中的CheckBox控件后该行背景变色”,于是找DataList做一下实验。

思路是这样的,先给table一个id,然后在绑定事件里把原id去掉,再重新加一个自己的id进去,最后调用js函数。

js如下:

 function CheckMe(chk,cell)

{

if(chk.checked)

      cell.style.backgroundColor="#ff9900";

else

     cell.style.backgroundColor="";

}

CS:

绑定数据后

 private void DtlWebList_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
  {
   int i=1;
   foreach(DataListItem _item in DtlWebList.Items)
   {
    System.Web.UI.HtmlControls.HtmlInputCheckBox chk=(System.Web.UI.HtmlControls.HtmlInputCheckBox)_item.FindControl("chkDel");
    System.Web.UI.HtmlControls.HtmlTable tab=(System.Web.UI.HtmlControls.HtmlTable)_item.FindControl("cell");

    tab.Attributes.Remove("id");
    ab.Attributes.Add("id","cell"+i.ToString());
    chk.Attributes.Add("onclick","cell"+i.ToString()+");");
    i+=1;
   }

  }

编译测试后发觉js报错,说cell未定义。百般无耐之下打开网页的源文件看了一下,发觉原来的table产生了两个id,一个是我自己的id:celli,一个是.net自己产生的id:DtlWebList__ctli._cell。其中i是自增长的记录号。

于是干脆重写cs:

 private void DtlWebList_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
  {
   int i=1;
   foreach(DataListItem _item in DtlWebList.Items)
   {
    System.Web.UI.HtmlControls.HtmlInputCheckBox chk=(System.Web.UI.HtmlControls.HtmlInputCheckBox)_item.FindControl("chkDel");

      chk.Attributes.Add("onclick","CheckMe(this,DtlWebList__ctl"+i.ToString()+"_cell);");
    i+=1;
   }

 }

编译,测试,成功了。

这方法有点笨,但大家在findControl find得有点迷糊的时候不妨打开源文件看看,会有新发现的。

原创粉丝点击