gridview全选反选,自定义分页,单选,导出导出到Excle


<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeFile="gridviewdemo.aspx.cs" Inherits="gridviewdemo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>51aspxGridView应用实例</title>

    <script language="javascript" type="text/javascript">   
    // 判断多选是否与选中项(没有选中的返回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)
    {
        if(objbeforeItem)
        {
            objbeforeItem.style.backgroundColor = objbeforeItembackgroundColor;
        }
        objbeforeItembackgroundColor = obj.style.backgroundColor;
        objbeforeItem = obj;
        obj.style.backgroundColor = "#B9D1F3";    
    }
    //       
 
    // 多选的全选与取消
    function checkJs(boolvalue)
    {
        if(document.all.checkboxname.length>1)
        {
            for(var i=0;i<document.all.checkboxname.length;i++)
            {
                document.all.checkboxname[i].checked = boolvalue;           
            }
        }
        else
            document.all.checkboxname.checked = boolvalue;
    }
    //
   
    // 只有全部选中时“全选”选中
    function SingleCheckJs()
    {
        var flag1=false;
        var flag2=false;
       
        if (document.form1.checkboxname.length)
        {
            for (var i=0;i<document.form1.checkboxname.length;i++)
            {
                if(document.form1.checkboxname[i].checked)
                    flag1 = true;
                else
                    flag2 = true;
            }
        }
        else
        {
            if(document.form1.checkboxname.checked)
                flag1 = true;
            else
                flag2 = true;
        }
       
        if(flag1==true&&flag2==false)
            document.getElementById("chk").checked = true;
        else
            document.getElementById("chk").checked = false;
    }
    //
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <table cellpadding="0" cellspacing="0" border="0" width="80%" style="font-size: 11px">
            <tr>
                <td align="center">
                    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px" CellPadding="4" EmptyDataText="没有数据记录!!" ForeColor="#333333" PageSize="12" ShowFooter="True" Width="100%" OnRowDataBound="GridView1_RowDataBound" OnSorting="GridView1_Sorting">
                        <Columns>
                            <asp:BoundField DataField="id" HeaderText="编号" Visible="False" />
                            <asp:TemplateField FooterText="全选" HeaderText="&lt;input type='checkbox' id='chk' name='chk' onclick='checkJs(this.checked);' /&gt;全选">
                                <ItemTemplate>
                                    <input type="checkbox" id="checkboxname" name="checkboxname" value='<%# DataBinder.Eval(Container.DataItem, "id")%>' onclick='SingleCheckJs();' />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField FooterText="单选" HeaderText="单选">
                                <ItemTemplate>
                                    <input type="radio" id="RadioName" name="RadioName" value='<%# Eval("id")%>' />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField FooterText="自增列" HeaderText="自增列">
                                <ItemTemplate>
                                    <%# (Container.DataItemIndex+1).ToString()%>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="name" HeaderText="姓名" FooterText="姓名" SortExpression="name" />
                            <asp:BoundField DataField="card" HeaderText="身份证号" FooterText="身份证号" SortExpression="card" />
                            <asp:BoundField DataField="price" DataFormatString="{0:¥#,##0.00}" HeaderText="价格" FooterText="价格" SortExpression="price" HtmlEncode="False" />
                            <asp:BoundField DataField="price" DataFormatString="{0:0.00}" FooterText="数字" HeaderText="数字" SortExpression="price" HtmlEncode="False" />
                            <asp:BoundField DataField="createdate" DataFormatString="{0:yyyy年MM月dd日 hh时mm分ss}" FooterText="建立时间"
                                HeaderText="建立时间" HtmlEncode="False" SortExpression="createdate" />
                        </Columns>
                        <PagerSettings Visible="False" />
                        <FooterStyle Font-Bold="True" />
                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                        <EditRowStyle BackColor="#999999" />
                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                    </asp:GridView>
                </td>
            </tr>
            <tr>
                <td align="center" style="height: 25px">
                    <asp:LinkButton ID="btnFirst" runat="server" CommandArgument="first" OnClick="PagerButtonClick">首 页</asp:LinkButton>
                    <asp:LinkButton ID="btnPrev" runat="server" CommandArgument="prev" OnClick="PagerButtonClick">上一页</asp:LinkButton>
                    <asp:LinkButton ID="btnNext" runat="server" CommandName="next" OnClick="PagerButtonClick">下一页</asp:LinkButton>
                    <asp:LinkButton ID="btnLast" runat="server" CommandArgument="last" OnClick="PagerButtonClick">尾页</asp:LinkButton>
                    <asp:Label ID="LblCurrentIndex" runat="server"></asp:Label>
                    <asp:Label ID="LblPageCount" runat="server"></asp:Label>
                    <asp:Label ID="LblRecordCount" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="Button1" runat="server" Text="checkbox得到选择的行" OnClick="Button1_Click" />
                    <asp:Button ID="Button2" runat="server" Text="radio得到选择的行" OnClick="Button2_Click" />
                    <asp:Button ID="Button3" runat="server" Text="导出到Excle" OnClick="Button3_Click" />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class gridviewdemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Attributes["onclick"] = "return slcNo_click();";
        GridViewBind("");
    }

    private void GridViewBind(string Sqlsort)
    {
        string connStr = ConfigurationManager.ConnectionStrings["Conn51aspx"].ConnectionString;
        string SqlStr = "select * from test01 where id<1000" + Sqlsort;
        DataSet ds = new DataSet();
        try
        {
            SqlConnection conn = new SqlConnection(connStr);
            if (conn.State.ToString() == "Closed")
            {
                conn.Open();
            }
            SqlDataAdapter da = new SqlDataAdapter(SqlStr, conn);
            da.Fill(ds, "test01");
            if (conn.State.ToString() == "Open")
            {
                conn.Close();
            }
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();
            LblCurrentIndex.Text = "第 " + Convert.ToString(GridView1.PageIndex + 1) + " 页";
            LblPageCount.Text = "共 " + GridView1.PageCount.ToString() + " 页";
            LblRecordCount.Text = "总共 " + ds.Tables[0].Rows.Count.ToString() + " 条";
            if (ds.Tables[0].Rows.Count == 0)
            {
                btnFirst.Visible = false;
                btnPrev.Visible = false;
                btnNext.Visible = false;
                btnLast.Visible = false;

                LblCurrentIndex.Visible = false;
                LblPageCount.Visible = false;
                LblRecordCount.Visible = false;
            }
            else if (GridView1.PageCount == 1)
            {
                btnFirst.Visible = false;
                btnPrev.Visible = false;
                btnNext.Visible = false;
                btnLast.Visible = false;
            }

            //计算生成分页页码,分别为:“首 页”“上一页”“下一页”“尾页”
            btnFirst.CommandName = "1";
            btnPrev.CommandName = (GridView1.PageIndex == 0 ? "1" : GridView1.PageIndex.ToString());
            btnNext.CommandName = (GridView1.PageCount == 1 ? GridView1.PageCount.ToString() : (GridView1.PageIndex + 2).ToString());
            btnLast.CommandName = GridView1.PageCount.ToString();
        }
        catch (Exception ex)
        {
            Response.Write("数据库错误:错误原因:" + ex.Message);
            Response.End();
        }
    }

    protected void PagerButtonClick(object sender, EventArgs e)
    {
        GridView1.PageIndex = Convert.ToInt32(((LinkButton)sender).CommandName) - 1;
        GridViewBind("");
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        e.Row.Attributes["onmouseover"] = "ItemOver(this)";
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
        }
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sql = "";
        if (ViewState["SortDirection"] == null || ViewState["SortDirection"].ToString().CompareTo("") == 0)
        {
            ViewState["SortDirection"] = " desc";
        }
        else
        {
            ViewState["SortDirection"] = "";
        }
        sql = " order by " + e.SortExpression + ViewState["SortDirection"];
        GridViewBind(sql);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string str = "";
        string[] ckb = null;
        str = Request.Form.Get("checkboxname");
        ckb = str.Split(new char[] { ',' });
        Response.Write("直接在页面中得到的值为:" + str + "<br>");
        Response.Write("处理后存放在数组中,如下:<br>");
        for (int i = 0; i < ckb.Length; i++)
        {
            Response.Write("ckb[" + i + "]的值为:" + ckb[i] + "<br>");
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Write(Request.Form.Get("RadioName"));
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
        Response.ContentType = "application/excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }

    public override void VerifyRenderingInServerForm(Control control)
    { }
}

关注微信公众号

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com