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


     

    在网络开发中,经常遇到需要使用ASP.NET与JavaScript联合进行控制的情况。在本篇中,将使用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() + ");");
     }
    }

    第四,完成之后运行程序。程序运行后,会在DataGrid控件的每行前显示一个CheckBox控件,选择该控件,该行背景颜色变蓝色,取消选择,该行颜色恢复初始状态。

  • 相关阅读:
    C# 文件夹的常用操作
    c语言学习笔记---预编译
    linux学习笔记
    c语言学习笔记---符号
    vim 编辑基础使用-----linux编程
    用pywinauto进行win32应用程序的测试
    Python中下划线的使用方法
    创建可维护的自动化验收测试
    Appium+Robotframework实现Android应用的自动化测试-1:Appium在Windows中的安装
    在中文windows下使用pywinauto进行窗口操作
  • 原文地址:https://www.cnblogs.com/xh831213/p/326523.html
Copyright © 2020-2023  润新知