datagrid的几点简单应用 (单选,多选.属标移动到上面颜色的改变等)

 Datagrid控件应该是用的很多的一种控件,下面简单写一下程序,简单说明一下其中的一些实用的功能.
关于datagrid的几点简单应用,功能包括radio的单选,checkbox的多选,鼠标移动到行上颜色变深,链接传递多参数等功能。这里radio和checkbox都使用的是HTML控件。
        有关checkbox的几个功能:全部选种、取消选种、没选中操作的检测等,这几个均使用js脚本实现

testdatagrid.aspx页面代码如下:

<%@ Page language="c#" Codebehind="testdatagrid.aspx.cs" AutoEventWireup="false" Inherits="testxml.testdatagrid" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<HTML>
  <HEAD>
        <title></title>
        <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
     <meta name="CODE_LANGUAGE" Content="C#">
       <meta name="vs_defaultClientScript" content="JavaScript">
        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
        <script language="javascript">
       //全部选中
      function QuanXuan_Click()
        {
          if (document.Form1.checkboxname.length){
                for (var i=0;i<document.Form1.checkboxname.length;i++){
                    document.Form1.checkboxname[i].checked = true;
               }
           }else{
               document.Form1.checkboxname.checked = true;
           }
      }
      
       //取消选中
       function QuXiao_Click()
       {
           if (document.Form1.checkboxname.length){
            for (var i=0;i<document.Form1.checkboxname.length;i++){
                   document.Form1.checkboxname[i].checked = false;
               }
           }else{
               document.Form1.checkboxname.checked = false;
           }
         }
        
         ///////////////判断没有选中的返回false
         function slcNo_click()
         {
             if (document.Form1.checkboxname.length){
                 for (var i=0;i<document.Form1.checkboxname.length;i++){
                     if(document.Form1.checkboxname[i].checked)
                     {
                         return true;
                     }
              }
             }else{
                 if(document.Form1.checkboxname.checked)
                 {
                     return true;
               }
           }
          alert("请选择后再操作!");
         return false;
     }
     
     //////////////////////////////////////改变行的颜色
       if (!objbeforeItem)
      {
           var objbeforeItem=null;
           var objbeforeItembackgroundColor=null;
       }
       function ItemOver(obj)
       {
           objbeforeItembackgroundColor=obj.style.backgroundColor;
           obj.style.backgroundColor="#B9D1F3";                                       
          objbeforeItem=obj;
       }
      
      function ItemOut(obj)
       {           
           if(objbeforeItem)
           {
               objbeforeItem.style.backgroundColor=objbeforeItembackgroundColor;
          }   
      }
      </script>
   </HEAD>
   <body MS_POSITIONING="GridLayout">
      <form id="Form1" method="post" runat="server">
          <table>
               <tr>
                    <td><FONT face="宋体"><asp:datagrid id="MyDataGrid" runat="server" Width="550px" AllowPaging="True" AutoGenerateColumns="False"
                            OnPageIndexChanged="MyDataGrid_Page" PageSize="5" CellPadding="2" HorizontalAlign="Left" BorderColor="Gray"
                             Font-Size="14px" Font-Names="新宋体">
                               <AlternatingItemStyle BackColor="#F2F2F2"></AlternatingItemStyle>
                              <ItemStyle Wrap="False" HorizontalAlign="Left" Height="22px" VerticalAlign="Middle"></ItemStyle>
                              <HeaderStyle Wrap="False" Height="25px" BackColor="#DEE6F6"></HeaderStyle>
                            <Columns>
                                <asp:BoundColumn Visible="False" DataField="id" SortExpression="id" HeaderText="id"></asp:BoundColumn>
                                  <asp:TemplateColumn>
                                    <HeaderTemplate>
                                           选择
                                       </HeaderTemplate>
                                      <ItemTemplate>
                                           <input type=radio name="RadioName" value='<%# DataBinder.Eval(Container.DataItem, "id")%>'/>
                                        </ItemTemplate>
                                  </asp:TemplateColumn>
                                   <asp:TemplateColumn>
                                      <HeaderTemplate>
                                          选择
                                     </HeaderTemplate>
                                      <ItemTemplate>
                                           <INPUT type="checkbox" name="checkboxname" value='<%# DataBinder.Eval(Container.DataItem, "id")%>'>
                                        </ItemTemplate>
                                   </asp:TemplateColumn>
                                    <asp:TemplateColumn>
                                       <HeaderTemplate>
                                            模板列
                                       </HeaderTemplate>
                                       <ItemTemplate>
                                           <asp:Label ID="lblId" Runat="server" Text=''>
                                           </asp:Label>
                                           <a href="abc.aspx?id=<%#DataBinder.Eval(Container.DataItem,  "id") %>&name=<%#DataBinder.Eval(Container.DataItem,  "name") %>" target="_blank">连接</a>
                                       </ItemTemplate>
                                   </asp:TemplateColumn>
                                   <asp:HyperLinkColumn DataNavigateUrlField="id" DataNavigateUrlFormatString="aa.aspx?id={0}" DataTextField="name"
                                        SortExpression="name" HeaderText="姓名" Target="_blank">
                                    </asp:HyperLinkColumn>
                                  <asp:BoundColumn DataField="card" SortExpression="card" HeaderText="身份证号" DataFormatString="{0:yyyy-MM-dd hh:mm:ss}"></asp:BoundColumn>
                                   <asp:BoundColumn DataField="price" SortExpression="price" HeaderText="价格"></asp:BoundColumn>
                                   <asp:BoundColumn DataField="shijian" SortExpression="shijian" HeaderText="shijian" DataFormatString="{0:yyyy年MM月dd日}"></asp:BoundColumn>
                               </Columns>
                              <PagerStyle Mode="NumericPages"></PagerStyle>
                           </asp:datagrid></FONT></td>
                </tr>
               <tr>
                  <td>
                        <asp:Button id="Button1" runat="server" Text="radio得到选择的行"></asp:Button>
                      <INPUT type="button" value="全部选中" onclick="QuanXuan_Click()">
                       <INPUT type="button" value="取消选中" onclick="QuXiao_Click()">
                     <asp:Button id="Button2" runat="server" Text="checkbox得到选择的行"></asp:Button>
                   </td>
              </tr>
            </table>
        </form>
    </body>
</HTML>


testdatagrid.aspx.cs代码如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;


namespace testxml
{
 /// <summary>
 /// testdatagrid 的摘要说明。
 /// </summary>
 public class testdatagrid : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.RadioButton RadioButton1;
     protected System.Web.UI.WebControls.Button Button1;
     protected System.Web.UI.WebControls.Button Button2;
  protected System.Web.UI.WebControls.DataGrid MyDataGrid;

  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面

   if (!IsPostBack)
             {
                 BindGrid();
             }
 
             Button2.Attributes.Add("OnClick","return slcNo_click();");

  }
  public void MyDataGrid_Page(object sender, DataGridPageChangedEventArgs e)
        
         {
            MyDataGrid.CurrentPageIndex = e.NewPageIndex;
            BindGrid();
         }

  private void BindGrid()
          
    {
              string strSql="";
             DataSet ds  = new DataSet();
              
             strSql="Select * from testDg";
              SqlConnection conn = new  SqlConnection(ConfigurationSettings.AppSettings["ConnStr"]);  
             if (conn.State.ToString() == "Closed")
            
                {
                 conn.Open();
             }
             
             SqlDataAdapter Da  = new SqlDataAdapter(strSql, conn);
             Da.Fill(ds, "tt");
            MyDataGrid.DataSource = ds.Tables["tt"].DefaultView;
             MyDataGrid.DataBind();
            
             Da.Dispose();
            if(conn.State.ToString()=="Open")
           
               {
                 conn.Close();
            }
             conn.Dispose();
      }
  private void MyDataGrid_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
         
  {
   //配合前台脚本实现鼠标移动到每行上变颜色//配合前台脚本实现鼠标移动到每行上变颜色
   #region   
   if(e.Item.ItemIndex>=0)
          
   {
    e.Item.Attributes.Add("onmouseover","ItemOver(this)");
    e.Item.Attributes.Add("onmouseout","ItemOut(this)");
   }
   #endregion
  }


  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.MyDataGrid.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.MyDataGrid_ItemCreated);
   this.Button1.Click += new System.EventHandler(this.Button1_Click);
   this.Button2.Click += new System.EventHandler(this.Button2_Click);
   this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion
  private void Button1_Click(object sender, System.EventArgs e)
         
             {
        Page.Response.Write(Page.Request.Form.Get("RadioName"));
         }
         private void Button2_Click(object sender, System.EventArgs e)
              
  {
          string str="";
          string []ckb=null;
          str=Page.Request.Form.Get("checkboxname");
          ckb=str.Split(new char[]{','});
     ;
             Page.Response.Write("直接在页面中得到的值为:"+str+"<br>");
 
             Page.Response.Write("处理后存放在数组中,如下:<br>");
             for(int i=0;i<ckb.Length;i++)
          
          {
              Page.Response.Write("ckb["+i+"]的值为:"+ckb[i]+"<br>");
       }
       }
 }
}


你可能感兴趣的:(datagrid)