关于datagrid的几点简单应用

        关于datagrid的几点简单应用,功能包括radio的单选,checkbox的多选,鼠标移动到行上颜色变深,链接传递多参数等功能。这里radio和checkbox都使用的是HTML控件。
        有关checkbox的几个功能:全部选种、取消选种、没选中操作的检测等,这几个均使用js脚本实现。
    
        运行效果图: 
             

        testdatagrid.aspx页面代码: 
  1 <% @ Page language="c#" Codebehind="testdatagrid.aspx.cs" AutoEventWireup="false" Inherits="localhost.fenpage.testdatagrid"  %>
  2 <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"  >
  3 < HTML >
  4      < HEAD >
  5          < title ></ title >
  6          < meta  name ="GENERATOR"  Content ="Microsoft Visual Studio .NET 7.1" >
  7          < meta  name ="CODE_LANGUAGE"  Content ="C#" >
  8          < meta  name ="vs_defaultClientScript"  content ="JavaScript" >
  9          < meta  name ="vs_targetSchema"  content ="http://schemas.microsoft.com/intellisense/ie5" >
 10          < script  language ="javascript" >
 11        //全部选中
 12        function QuanXuan_Click()
 13        {
 14            if (document.Form1.checkboxname.length){
 15                for (var i=0;i<document.Form1.checkboxname.length;i++){
 16                    document.Form1.checkboxname[i].checked = true;
 17                }

 18            }
else{
 19                document.Form1.checkboxname.checked = true;
 20            }

 21        }

 22        
 23        //取消选中
 24        function QuXiao_Click()
 25        {
 26            if (document.Form1.checkboxname.length){
 27                for (var i=0;i<document.Form1.checkboxname.length;i++){
 28                    document.Form1.checkboxname[i].checked = false;
 29                }

 30            }
else{
 31                document.Form1.checkboxname.checked = false;
 32            }

 33        }

 34        
 35        ///判断没有选中的返回false
 36        function slcNo_click()
 37        {
 38            if (document.Form1.checkboxname.length){
 39                for (var i=0;i<document.Form1.checkboxname.length;i++){
 40                    if(document.Form1.checkboxname[i].checked)
 41                    {
 42                        return true;
 43                    }

 44                }

 45            }
else{
 46                if(document.Form1.checkboxname.checked)
 47                {
 48                    return true;
 49                }

 50            }

 51            alert("请选择后再操作!");
 52            return false;
 53        }

 54        
 55        //改变行的颜色
 56        if (!objbeforeItem)
 57        {
 58            var objbeforeItem=null;
 59            var objbeforeItembackgroundColor=null;
 60        }

 61        function ItemOver(obj)
 62        {
 63            objbeforeItembackgroundColor=obj.style.backgroundColor;
 64            obj.style.backgroundColor="#B9D1F3";                                        
 65            objbeforeItem=obj;
 66        }

 67        
 68        function ItemOut(obj)
 69        {            
 70            if(objbeforeItem)
 71            {
 72                objbeforeItem.style.backgroundColor=objbeforeItembackgroundColor;
 73            }
    
 74        }

 75        
</ script >
 76      </ HEAD >
 77      < body  MS_POSITIONING ="GridLayout" >
 78          < form  id ="Form1"  method ="post"  runat ="server" >
 79              < table >
 80                  < tr >
 81                      < td >< FONT  face ="宋体" >< asp:datagrid  id ="MyDataGrid"  runat ="server"  Width ="550px"  AllowPaging ="True"  AutoGenerateColumns ="False"
 82                                 OnPageIndexChanged ="MyDataGrid_Page"  PageSize ="10"  CellPadding ="2"  HorizontalAlign ="Left"  BorderColor ="Gray"
 83                                 Font-Size ="14px"  Font-Names ="新宋体" >
 84                                  < AlternatingItemStyle  BackColor ="#F2F2F2" ></ AlternatingItemStyle >
 85                                  < ItemStyle  Wrap ="False"  HorizontalAlign ="Left"  Height ="22px"  VerticalAlign ="Middle" ></ ItemStyle >
 86                                  < HeaderStyle  Wrap ="False"  Height ="25px"  BackColor ="#DEE6F6" ></ HeaderStyle >
 87                                  < Columns >
 88                                      < asp:BoundColumn  Visible ="False"  DataField ="id"  SortExpression ="id"  HeaderText ="id" ></ asp:BoundColumn >
 89                                      < asp:TemplateColumn >
 90                                          < HeaderTemplate >
 91                                             选择
 92                                          </ HeaderTemplate >
 93                                          < ItemTemplate >
 94                                              < input  type =radio  name ="RadioName"  value ='<%#  DataBinder.Eval(Container.DataItem, "id")% > '/>
 95                                          </ ItemTemplate >
 96                                      </ asp:TemplateColumn >
 97                                      < asp:TemplateColumn >
 98                                          < HeaderTemplate >
 99                                             选择
100                                          </ HeaderTemplate >
101                                          < ItemTemplate >
102                                              < INPUT  type ="checkbox"  name ="checkboxname"  value ='<%#  DataBinder.Eval(Container.DataItem, "id")% > '>
103                                          </ ItemTemplate >
104                                      </ asp:TemplateColumn >
105                                      < asp:TemplateColumn >
106                                          < HeaderTemplate >
107                                             模板列
108                                          </ HeaderTemplate >
109                                          < ItemTemplate >
110                                              < asp:Label  ID ="lblId"  Runat ="server"  Text ='' >
111                                              </ asp:Label >
112                                              < href ="abc.aspx?id=<%#DataBinder.Eval(Container.DataItem,  " id") % > &name = <% #DataBinder.Eval(Container.DataItem,  "name" %> " target="_blank">连接 </ a >
113                                          </ ItemTemplate >
114                                      </ asp:TemplateColumn >
115                                      < asp:HyperLinkColumn  DataNavigateUrlField ="id"  DataNavigateUrlFormatString ="aa.aspx?id={0}"  DataTextField ="name"
116                                         SortExpression ="name"  HeaderText ="姓名"  Target ="_blank" >
117                                      </ asp:HyperLinkColumn >
118                                      < asp:BoundColumn  DataField ="card"  SortExpression ="card"  HeaderText ="身份证号"  DataFormatString ="{0:yyyy-MM-dd hh:mm:ss}" ></ asp:BoundColumn >
119                                      < asp:BoundColumn  DataField ="price"  SortExpression ="price"  HeaderText ="价格" ></ asp:BoundColumn >
120                                      < asp:BoundColumn  DataField ="shijian"  SortExpression ="shijian"  HeaderText ="shijian"  DataFormatString ="{0:yyyy年MM月dd日}" ></ asp:BoundColumn >
121                                  </ Columns >
122                                  < PagerStyle  Mode ="NumericPages" ></ PagerStyle >
123                              </ asp:datagrid ></ FONT ></ td >
124                  </ tr >
125                  < tr >
126                      < td >
127                          < asp:Button  id ="Button1"  runat ="server"  Text ="radio得到选择的行" ></ asp:Button >
128                          < INPUT  type ="button"  value ="全部选中"  onclick ="QuanXuan_Click()" >
129                          < INPUT  type ="button"  value ="取消选中"  onclick ="QuXiao_Click()" >
130                          < asp:Button  id ="Button2"  runat ="server"  Text ="checkbox得到选择的行" ></ asp:Button >
131                      </ td >
132                  </ tr >
133              </ table >
134          </ form >
135      </ body >
136 </ HTML >
137

        testdatagrid.aspx.cs页面代码:
  1 using  System;
  2 using  System.Collections;
  3 using  System.ComponentModel;
  4 using  System.Data;
  5 using  System.Data.SqlClient;
  6 using  System.Drawing;
  7 using  System.Web;
  8 using  System.Web.SessionState;
  9 using  System.Web.UI;
 10 using  System.Web.UI.WebControls;
 11 using  System.Web.UI.HtmlControls;
 12 using  System.Configuration;
 13
 14 namespace  localhost.fenpage
 15 {
 16    /// <summary>
 17    /// testdgRadio 的摘要说明。
 18    /// </summary>

 19    public class testdatagrid : System.Web.UI.Page
 20    {
 21        protected System.Web.UI.WebControls.RadioButton RadioButton1;
 22        protected System.Web.UI.WebControls.Button Button1;
 23        protected System.Web.UI.WebControls.Button Button2;
 24        protected System.Web.UI.WebControls.DataGrid MyDataGrid;
 25    
 26        private void Page_Load(object sender, System.EventArgs e)
 27        {            
 28            if (!IsPostBack)
 29            {
 30                BindGrid();
 31            }

 32
 33            Button2.Attributes.Add("OnClick","return slcNo_click();");
 34        }

 35
 36        public void MyDataGrid_Page(object sender, DataGridPageChangedEventArgs e)
 37        {
 38            MyDataGrid.CurrentPageIndex = e.NewPageIndex;
 39            BindGrid();
 40        }

 41
 42        private void BindGrid()
 43        {
 44            string strSql="";
 45            DataSet ds  = new DataSet();
 46            
 47            strSql="Select * from testDg";
 48            SqlConnection conn = new  SqlConnection(ConfigurationSettings.AppSettings["ConnStr"]);  
 49            if (conn.State.ToString() == "Closed")
 50            {
 51                conn.Open();
 52            }

 53            
 54            SqlDataAdapter Da  = new SqlDataAdapter(strSql, conn);
 55            Da.Fill(ds, "testdg");
 56            MyDataGrid.DataSource = ds.Tables["testdg"].DefaultView;
 57            MyDataGrid.DataBind();
 58            
 59            Da.Dispose();
 60            if(conn.State.ToString()=="Open")
 61            {
 62                conn.Close();
 63            }

 64            conn.Dispose();
 65        }

 66
 67        private void MyDataGrid_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
 68        {
 69            #region    //配合前台脚本实现鼠标移动到每行上变颜色
 70            if(e.Item.ItemIndex>=0)
 71            {
 72                e.Item.Attributes.Add("onmouseover","ItemOver(this)");//在每行上增加脚本处理 onmouseover
 73                e.Item.Attributes.Add("onmouseout","ItemOut(this)");//在每行上增加脚本处理 onmouseout
 74            }

 75            #endregion

 76        }

 77
 78        #region Web 窗体设计器生成的代码
 79        override protected void OnInit(EventArgs e)
 80        {
 81            //
 82            // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
 83            //
 84            InitializeComponent();
 85            base.OnInit(e);
 86        }

 87        
 88        /// <summary>
 89        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
 90        /// 此方法的内容。
 91        /// </summary>

 92        private void InitializeComponent()
 93        {    
 94            this.MyDataGrid.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.MyDataGrid_ItemCreated);
 95            this.Button1.Click += new System.EventHandler(this.Button1_Click);
 96            this.Button2.Click += new System.EventHandler(this.Button2_Click);
 97            this.Load += new System.EventHandler(this.Page_Load);
 98
 99        }

100        #endregion

101
102        private void Button1_Click(object sender, System.EventArgs e)
103        {
104            Page.Response.Write(Page.Request.Form.Get("RadioName"));
105        }

106
107        private void Button2_Click(object sender, System.EventArgs e)
108        {
109            string str="";
110            string []ckb=null;
111
112            str=Page.Request.Form.Get("checkboxname");
113            ckb=str.Split(new char[]{','});
114
115            Page.Response.Write("直接在页面中得到的值为:"+str+"<br>");
116
117            Page.Response.Write("处理后存放在数组中,如下:<br>");
118            for(int i=0;i<ckb.Length;i++)
119            {
120                Page.Response.Write("ckb["+i+"]的值为:"+ckb[i]+"<br>");
121            }

122        }

123    }

124}

125

        生成数据库表用到的sql语句:
CREATE   TABLE   [ dbo ] . [ testDg ]  (
    
[ id ]   [ decimal ] ( 18 0 IDENTITY  ( 1 1 NOT   NULL  ,
    
[ name ]   [ varchar ]  ( 50 ) COLLATE Chinese_PRC_CI_AS  NULL  ,
    
[ card ]   [ varchar ]  ( 50 ) COLLATE Chinese_PRC_CI_AS  NULL  ,
    
[ price ]   [ numeric ] ( 18 2 NULL  ,
    
[ shijian ]   [ datetime ]   NULL  
ON   [ PRIMARY ]
GO

ALTER   TABLE   [ dbo ] . [ testDg ]   ADD  
    
CONSTRAINT   [ DF_testDg_shijian ]   DEFAULT  ( getdate ())  FOR   [ shijian ] ,
    
CONSTRAINT   [ PK_testDg ]   PRIMARY   KEY    CLUSTERED  
    (
        
[ id ]
    )  
ON   [ PRIMARY ]  
GO
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值