在网络开发中,经常遇到需要使用ASP.NET与javascript联合进行控制的情况。就像163邮箱一样,选中checkbox后即变色,在数据很多的情况下,可以让用户很精确的选中哪一行,不导致删除数据的错误。将使用DataGrid进行数据绑定,使用javascript控制当选中其中的checkbox时,该行颜色改变。

首先,在页面中创建一个DataGrid控件,并设置其模板。

<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox id="checkbox1" Runat ="server"></asp:CheckBox>
<asp:Label  runat="server" Text='<%# DataBinder.Eval(Container, "DataItem") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>


第二,在页面中的<head></head>中编写javascript脚本函数,进行CheckBox的判断和颜色改变的控制。

<script>  
   
function checkme(obj,tr){
   
if(obj.checked)
      tr.style.backgroundColor
='blue';
   
else
      tr.style.backgroundColor
='';
    }

    
</script>  

第三,在Page_Load事件中为DataGrid绑定数据,并关联CheckBox的javascript脚本。

private void Page_Load(object sender, System.EventArgs e)
{
 
// Put user code to initialize the page here
 if(!IsPostBack)
 
{
  databind();
 }

}


private void databind()
{
 ArrayList arr
=new ArrayList();
 arr.Add(
"新闻综合");
 arr.Add(
"综艺");
 arr.Add(
"电影");
 arr.Add(
"教育");
 arr.Add(
"戏剧");
 arr.Add(
"军事");
 arr.Add(
"体育");
 DataGrid1.DataSource
=arr;
 DataGrid1.DataBind();  
 
int i;
 
for(i=0;i<DataGrid1.Items.Count;i++){
  CheckBox cb;
  cb
=(CheckBox)DataGrid1.Items[i].FindControl("checkbox1"); 
  DataGrid1.Items[i].Attributes.Add(
"id","tr" + i.ToString()); 
  cb.Attributes.Add(
"onclick","checkme(this,tr" + i.ToString() + ");"); 
 }

}




 

posted on 2008-04-01 14:14  Smthhy  阅读(570)  评论(0编辑  收藏  举报