• 前面几篇文章有关DataGrid的所有代码


    有网友向我索取代码,现在帖出所有
    这个DataGrid包含以下功能的示范:
    添加、删除、修改、分页、下载数据到客户端、合计、筛选记录、单选、多选。

    数据库表名:tb1,其中有3个字段,分别是ID自增的主键、vName varchar(50)、iAge int

    客户端代码:
    <%@ Page language="c#" Codebehind="WebForm5.aspx.cs" AutoEventWireup="false" Inherits="csdn.WebForm5" %>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
       
    <HEAD>
           
    <title>WebForm5</title>
           
    <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
           
    <meta content="C#" name="CODE_LANGUAGE">
           
    <meta content="JavaScript" name="vs_defaultClientScript">
           
    <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
       
    </HEAD>
       
    <body>
           
    <form id="Form1" method="post" runat="server">
               
    <input type="hidden" id="rd" runat="server" name="rd">
               
    <asp:textbox id="TextBox1" runat="server" Width="88px"></asp:textbox>
               
    <asp:TextBox id="TextBox2" runat="server" Width="40px"></asp:TextBox>
               
    <asp:Button id="Button1" runat="server" Text="添加"></asp:Button>
               
    <asp:TextBox id="TextBox3" runat="server" Width="128px"></asp:TextBox>
               
    <asp:Button id="Button2" runat="server" Text="筛选"></asp:Button>
               
    <asp:Button id="Button3" runat="server" Text="下载"></asp:Button>
               
    <asp:datagrid id="DataGrid1" runat="server" AutoGenerateColumns="False" DataKeyField="ID" AllowPaging="True"
                    PageSize
    ="20" OnEditCommand="edit" OnCancelCommand="cancel" OnUpdateCommand="update">
                   
    <Columns>
                       
    <asp:TemplateColumn HeaderText="多选">
                           
    <ItemTemplate>
                               
    <input type="hidden" id="SelectedID" runat="server"
                    value
    ='<%# Container.ItemIndex%>
    '  NAME="SelectedID"/>
                               
    <asp:CheckBox ID="chkExport" Runat="server" />

                           
    </ItemTemplate>
                       
    </asp:TemplateColumn>
                       
    <asp:TemplateColumn HeaderText="单选">
                           
    <ItemTemplate>
                               
    <%# Container.ItemIndex+1%>
                               
    <input type=radio name="rad" value='<%# Container.ItemIndex+1%>'>
                           
    </ItemTemplate>

                       
    </asp:TemplateColumn>
                       
    <asp:TemplateColumn HeaderText="姓名">
                           
    <ItemTemplate>
                               
    <%# myfunc(DataBinder.Eval(Container.DataItem,"vName")) %>
                           
    </ItemTemplate>
                           
    <EditItemTemplate>
                               
    <asp:TextBox id="name" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"vName") %>' Width="88px">
                               
    </asp:TextBox>

                           
    </EditItemTemplate>
                       
    </asp:TemplateColumn>
                       
    <asp:TemplateColumn HeaderText="年龄">
                           
    <ItemTemplate>
                               
    <%# DataBinder.Eval(Container.DataItem,"iAge") %>
                           
    </ItemTemplate>
                           
    <EditItemTemplate>
                               
    <asp:TextBox id="age" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"iAge") %>' Width="40px">
                               
    </asp:TextBox>

                           
    </EditItemTemplate>
                       
    </asp:TemplateColumn>
                       
    <asp:TemplateColumn HeaderText="打开">
                           
    <ItemTemplate>
                               
    <asp:HyperLink Text="打开" NavigateUrl='<%#"newpage.aspx?name="+DataBinder.Eval(Container.DataItem, "vname")+"&age="+DataBinder.Eval(Container.DataItem, "iage") %>' Runat="server" Target="_blank">
                               
    </asp:HyperLink>

                           
    </ItemTemplate>
                       
    </asp:TemplateColumn>
                       
    <asp:TemplateColumn HeaderText="打开">
                           
    <ItemTemplate>
                               
    <asp:HyperLink Text="打开" NavigateUrl='<%# myfunc2(DataBinder.Eval(Container.DataItem,"vName"),DataBinder.Eval(Container.DataItem,"iAge"))%> ' Runat="server" Target="_blank" ID="Hyperlink1">
                               
    </asp:HyperLink>

                           
    </ItemTemplate>
                       
    </asp:TemplateColumn>
                       
    <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="更新" CancelText="取消" EditText="编辑"></asp:EditCommandColumn>
                       
    <asp:ButtonColumn Text="删除" CommandName="del"></asp:ButtonColumn>
                   
    </Columns>
                   
    <PagerStyle Mode="NumericPages"></PagerStyle>
               
    </asp:datagrid>
               
    <asp:Label id="Label1" runat="server"></asp:Label>
               
    <asp:Button id="button4" runat="server" Text="单选结果"></asp:Button>
               
    <asp:Button id="Button5" runat="server" Text="多选结果"></asp:Button>
               
    <asp:Button id="Button6" runat="server" Text="选中所有"></asp:Button>
               
    <asp:Button id="Button7" runat="server" Text="取消所有"></asp:Button></form>
       
    </body>
    </HTML>
    服务端代码:
    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.IO;

    namespace
    csdn
    {
       
    /// <summary>
       
    /// WebForm5 的摘要说明。
       
    /// </summary>

        public class WebForm5 : System.Web.UI.Page
       
    {
           
    protected
    System.Web.UI.WebControls.TextBox TextBox1;
           
    protected
    System.Web.UI.WebControls.TextBox TextBox2;
           
    protected
    System.Web.UI.WebControls.Button Button1;
           
    protected
    System.Web.UI.WebControls.TextBox TextBox3;
           
    protected
    System.Web.UI.WebControls.Button Button2;
           
    protected
    System.Web.UI.WebControls.Button Button3;
           
    protected
    System.Web.UI.WebControls.Label Label1;
           
    protected
    System.Web.UI.HtmlControls.HtmlInputHidden rd;
           
    protected
    System.Web.UI.WebControls.Button button4;
           
    protected
    System.Web.UI.WebControls.Button Button5;
           
    protected
    System.Web.UI.WebControls.Button Button6;
           
    protected
    System.Web.UI.WebControls.DataGrid DataGrid1;
           
    protected
    System.Web.UI.WebControls.Button Button7;
       
       
           
    private void Page_Load(object
    sender, System.EventArgs e)
           
    {

               
    string js = ""
    ;
                js
    +="<script>\r\n"
    ;
                js
    +="function ld(){\r\n"
    ;
                js
    +="for(i=0;i<document.getElementsByName('rad').length;i++)\r\n"
    ;
                js
    +="if(document.getElementsByName('rad')[i].value=="
    ;
                js
    +="document.getElementById('rd').value) "
    ;
                js
    +="document.getElementsByName('rad')[i].checked=true\r\n"
    ;
                js
    +="}\r\n"
    ;
                js
    +="window.onload=ld\r\n"
    ;
                js
    +="</script>\r\n"
    ;
               
    this.RegisterClientScriptBlock("js"
    ,js);

               
    if(!
    IsPostBack)
               
    {
                    SetBind();
                }

               
            }


           
    protected void SetBind()
           
    {

                SqlConnection conn
    =new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"
    ]);
                SqlDataAdapter da
    =new SqlDataAdapter("select * from tb1"
    ,conn);
                DataSet ds
    =new
    DataSet();
                da.Fill(ds,
    "table1"
    );
               
    this.DataGrid1.DataSource=ds.Tables["table1"
    ];
               
    this
    .DataGrid1.DataBind();
               
    this.Label1.Text=ds.Tables["table1"].Compute("avg(iAge)","iAge>20"
    ).ToString();
            }


           
    protected void SetBind(string s)
           
    {
                SqlConnection conn
    =new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"
    ]);
                SqlDataAdapter da
    =new SqlDataAdapter("select * from tb1"
    ,conn);
                DataSet ds
    =new
    DataSet();
                da.Fill(ds,
    "table1"
    );
                DataView dv
    =ds.Tables["table1"
    ].DefaultView;
                dv.RowFilter
    =
    s;
               
    this.DataGrid1.DataSource=
    dv;
               
    this
    .DataGrid1.DataBind();
            }


           
    Web 窗体设计器生成的代码
    this.DataGrid1.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemCreated);
       this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
       this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
       this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);

            }

           
    #endregion


           
    private void Button1_Click(object sender, System.EventArgs e)
           
    {
                SqlConnection conn
    =new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"
    ]);
                SqlCommand comm
    =new SqlCommand("insert into tb1 (vName,iAge) values (@vName,@iAge)"
    ,conn);
                SqlParameter parm1
    =new SqlParameter("@vName",SqlDbType.NVarChar,50
    );
                parm1.Value
    =this
    .TextBox1.Text;
                SqlParameter parm2
    =new SqlParameter("@iAge"
    ,SqlDbType.Int);
                parm2.Value
    =this
    .TextBox2.Text;
                comm.Parameters.Add(parm1);
                comm.Parameters.Add(parm2);
                conn.Open();
                comm.ExecuteNonQuery();
                conn.Close();
                SetBind();
            }


           
    private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
           
    {
               
    if(e.CommandName=="del"&&e.Item.ItemType!=
    ListItemType.EditItem)
               
    {
                    SqlConnection conn
    =new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"
    ]);
                    SqlCommand comm
    =new SqlCommand("delete from tb1 where ID=@id"
    ,conn);
                    SqlParameter parm1
    =new SqlParameter("@id"
    ,SqlDbType.Int);
                    parm1.Value
    =this
    .DataGrid1.DataKeys[e.Item.ItemIndex];
                    comm.Parameters.Add(parm1);
                    conn.Open();
                    comm.ExecuteNonQuery();
                    conn.Close();
                    SetBind();
                }

            }


           
    private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
           
    {
               
    this.DataGrid1.CurrentPageIndex=
    e.NewPageIndex;
                SetBind();
            }


           
    protected void edit(object sender,DataGridCommandEventArgs e)
           
    {
               
    this.DataGrid1.EditItemIndex=
    e.Item.ItemIndex;
                SetBind();
            }


           
    protected void cancel(object sender,DataGridCommandEventArgs e)
           
    {
               
    this.DataGrid1.EditItemIndex=-1
    ;
                SetBind();
            }


           
    protected void update(object sender,DataGridCommandEventArgs e)
           
    {
               
    if(e.Item.ItemType==
    ListItemType.EditItem)
               
    {
                    SqlConnection conn
    =new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"
    ]);
                    SqlCommand comm
    =new SqlCommand("update tb1 set vName=@vName,iAge=@iAge where ID=@id"
    ,conn);
                    SqlParameter parm1
    =new SqlParameter("@vName",SqlDbType.NVarChar,50
    );
                    parm1.Value
    =((TextBox)e.Item.FindControl("name"
    )).Text;
                    SqlParameter parm2
    =new SqlParameter("@iAge"
    ,SqlDbType.Int);
                    parm2.Value
    =((TextBox)e.Item.FindControl("age"
    )).Text;
                    SqlParameter parm3
    =new SqlParameter("@id"
    ,SqlDbType.Int);
                    parm3.Value
    =this
    .DataGrid1.DataKeys[e.Item.ItemIndex];
                    comm.Parameters.Add(parm1);
                    comm.Parameters.Add(parm2);
                    comm.Parameters.Add(parm3);
                    conn.Open();
                    comm.ExecuteNonQuery();
                    conn.Close();
                   
    this.DataGrid1.EditItemIndex=-1
    ;
                    SetBind();
                }

            }


           
    private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
           
    {
               
                   
    if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem||e.Item.ItemType==
    ListItemType.EditItem)
                   
    {
                        ((LinkButton)e.Item.Cells[
    7].Controls[0]).Attributes.Add("onclick","return confirm('delete?');"
    );
                    }

               
            }


           
    private void Button2_Click(object sender, System.EventArgs e)
           
    {
               
    if(this.TextBox3.Text==""
    )
               
    {
                    SetBind();
                }

               
    else
               
    {
                    SetBind(
    this
    .TextBox3.Text);
                }

            }


           
    private void DataGrid1_SelectedIndexChanged(object sender, System.EventArgs e)
           
    {
               
            }


           
    private void Button3_Click(object sender, System.EventArgs e)
           
    {
                SqlConnection conn
    =new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"
    ]);
                SqlDataAdapter da
    =new SqlDataAdapter("select * from tb1"
    ,conn);
                DataSet ds
    =new
    DataSet();
                da.Fill(ds,
    "table1"
    );
                DataTable dt
    =ds.Tables["table1"
    ];
               
    string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv"
    ;
                FileStream fs
    =new
    FileStream(name,FileMode.Create,FileAccess.Write);
                StreamWriter sw
    =new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"
    ));
                sw.WriteLine(
    "自动编号,姓名,年龄"
    );
               
    foreach(DataRow dr in
    dt.Rows)
               
    {
                    sw.WriteLine(dr[
    "ID"]+","+dr["vName"]+","+dr["iAge"
    ]);
                }

                sw.Close();
                Response.AddHeader(
    "Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
                Response.ContentType
    = "application/ms-excel"
    ;
                Response.WriteFile(name);
                Response.End();
            }


           
    private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
           
    {
               
    if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem||e.Item.ItemType==
    ListItemType.EditItem)
               
    {
                   
    if(Convert.ToInt16(DataBinder.Eval(e.Item.DataItem,"iAge"))<30)e.Item.BackColor=
    Color.Pink;
       
                }

            }


           
    protected string myfunc(object s)
           
    {
               
    string
    _s;
               
    if(s.ToString()=="朱晔"
    )
                    _s
    ="<b>"+s.ToString()+"</b>"
    ;
               
    else

                    _s
    =s.ToString();
               
    return
    _s;
            }


           
    protected string myfunc2(object s1,object s2)
           
    {
               
    return "newpage.aspx?name="+s1.ToString()+"&age="+
    s2.ToString();
            }


           
    private void Button4_Click(object sender, System.EventArgs e)
           
    {
               
    if(Request.Form["rad"] != null
    )
               
    {
                    rd.Value
    = Request.Form["rad"
    ].ToString();

                   
    this.Label1.Text = "选择的行号:" + Request.Form["rad"
    ].ToString();
                }


           
            }



           
    private void Button5_Click(object sender, System.EventArgs e)
           
    {
               
    this.Label1.Text=""
    ;
               
    foreach(DataGridItem di in this
    .DataGrid1.Items)
               
    {
                   
    if(((CheckBox)di.FindControl("chkExport")).Checked==true
    )
                   
    {
                       
    this.Label1.Text+=this.DataGrid1.DataKeys[int.Parse(((HtmlInputHidden)di.FindControl("SelectedID")).Value)]+"<br>"
    ;
                    }

                }

            }


           
    private void Button6_Click(object sender, System.EventArgs e)
           
    {
               
    foreach(DataGridItem di in this
    .DataGrid1.Items)
               
    {
                   
                    ((CheckBox)di.FindControl(
    "chkExport")).Checked=true
    ;
                   
                }

            }


           
    private void Button7_Click(object sender, System.EventArgs e)
           
    {
               
    foreach(DataGridItem di in this
    .DataGrid1.Items)
               
    {
                   
                    ((CheckBox)di.FindControl(
    "chkExport")).Checked=false
    ;
                   
                }

           
            }

        }


    不好意思
    vs.net吃掉了一些事件注册
    补上:
    this.DataGrid1.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemCreated);
    this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
    this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
    this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);


  • 相关阅读:
    Json.Net学习笔记(八) 序列化的回调方法
    PowerDesigner 使用的一些技巧(转)
    Json.Net学习笔记(十三) 缩小序列化Json的大小
    Json.Net学习笔记(十四) JSON的部分序列化
    MSDTC服务配置 今天碰到的情况
    Json.Net学习笔记(十一) CustomCreationConverter
    让工作自动化
    Json.Net学习笔记(十二) 协议解析
    Json.Net学习笔记(九) 异常处理
    通过PB认证
  • 原文地址:https://www.cnblogs.com/lovecherry/p/125518.html
Copyright © 2020-2023  润新知