Gridview数据绑定基于按钮单击

时间:2014-04-08 15:50:13

标签: c# asp.net

我的页面中有以下内容。

  • 2个Asp Buttons
  • 1 GridView
  • 1个用于导出到Excel的图像按钮

我需要根据各自的按钮查看gridview。即每个按钮将显示不同的数据。 gridview应该允许分页,因为有很多记录。单击图像按钮(包括gridview中的所有页面)时,也应该导出到Excel。任何人都可以帮忙吗?

我的代码正在关注

aspx文件。

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <div>
     <table id="Table2" width="100%" align="left" runat="server">
      <tr>
        <td class="auto-style8">
        </td>
         <td class="auto-style9"></td><td class="auto-style10">
             <asp:Button ID="Admin" runat="server" Text="Admin" TOOLTIP="Sign In" TABINDEX="3"  BackColor="Gray" BorderColor="Black" BorderStyle="Groove" Font-Bold="True" Font-Names="Arial" Font-Size="Large" ForeColor="White" Height="46px" Width="85px"/>
                <asp:Menu ID="Menu1" runat="server" StaticSubMenuIndent="" Font-Bold="True" Font-Size="Large">
                <Items>
                    <asp:MenuItem Text="Home" Value="Home" NavigateUrl="Admin_Main.aspx"></asp:MenuItem>
                    <asp:MenuItem Text="Add Customer" Value="Add Customer" NavigateUrl="Add_Details.aspx"></asp:MenuItem>
                    <asp:MenuItem Text="Delete Customer" Value="Delete Customer" NavigateUrl="Delete_Customer.aspx"></asp:MenuItem>

                </Items>

             </asp:Menu>   
             <asp:LinkButton ID="logout" runat="server" OnClick="logout_click" Font-Bold="True" Font-Size="Large">Logout</asp:LinkButton>
         </td>
          </tr>
          </table>
          </div>
          <div>
     <asp:Label ID="Label1" runat="server" Text="UserName" Font-Bold="True" 
                  Font-Size="X-Large"></asp:Label>
     <asp:TextBox ID="userName" Name= "userName"  runat="server" Font-Bold="True"></asp:TextBox>

     </div>
     <div>
      <asp:Button ID="Button2" runat="server" Text="Email Log" OnClick= "Email_Click" Height="35px" Font-Bold="True" Font-Size="Medium" Width="90px"/>
    <asp:Button ID="Button1" runat="server" Text="All Log" Height="35px" OnClick= "Log_Click" Font-Bold="True" Font-Size="Medium" Width="90px"/>
    <asp:ImageButton ID="btnexport" runat="server" Height="35px" ImageUrl="~/Images/exp-xls.gif" Width="112px" OnClick="btnExport_Click" Visible="false" />
     </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>

</asp:Content>

aspx.cs文件

public partial class Display_Log : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string user = (string)(Session["user"]);
        if (!IsPostBack)
        {
            if (user == null)
            {
                Response.Redirect("~/InvalidLogin.aspx");
            }
            else
            {
                Admin.Text = user;
                Admin.Enabled = false;
            }
        }
    }
    protected void Email_Click(object sender, EventArgs e)
    {

        SqlConnection cnn = new SqlConnection();
        string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
        cnn.ConnectionString = connStr;
        cnn.Open();
        String sqlSelect = String.Format(" Select Customer_Name,Time_Send_Clicked,Reminder_Type from Email_Log where Username='{0}'",userName.Text.ToString().Trim());
        SqlCommand myCommand = new SqlCommand(sqlSelect, cnn);
        SqlDataAdapter da = new SqlDataAdapter(myCommand);
        DataTable dt = new DataTable();
        da.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
        cnn.Close();
        btnexport.Visible = true;



    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename=ActivityReport_" + userName.Text + ".xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
          GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }

    protected void Log_Click(object sender, EventArgs e)
    {
        SqlConnection cnn = new SqlConnection();
        string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
        cnn.ConnectionString = connStr;
        cnn.Open();
        String sqlSelect = String.Format(" SELECT [Activity],[Time],[Ticket_Number] FROM Log where Username='{0}'", userName.Text.ToString().Trim());
        SqlCommand myCommand = new SqlCommand(sqlSelect, cnn);
        SqlDataAdapter da = new SqlDataAdapter(myCommand);
        DataTable dt = new DataTable();
        da.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
        cnn.Close();
        btnexport.Visible = true;
    }
    protected void logout_click(object sender, EventArgs e)
    {

        this.Session["user"] = null;
        this.Session["group"] = null;
        Response.Redirect("~/Default.aspx");
    }
}

1 个答案:

答案 0 :(得分:0)

要添加pagging你需要指定AllowPaging="True"这将添加pagging但它不会工作,直到你指定这个处理onclick事件时单击页面按钮     onpageindexchanging="GridView1_PageIndexChanging"

<asp:GridView ID="GridView1"AutoGenerateColumns="false" DataKeyNames="Identityrowoftable" AllowPaging="True" 
onpageindexchanging="GridView1_PageIndexChanging" />

在后面的代码中添加此

 protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        // you need to rebind gridview here 
        //just set the source and databind
    }

之后的打印部分

首先,您需要清除控件,以便在打印时不会出现不需要的元素。

private void ClearControls(Control control)
    {
        for (int i = control.Controls.Count - 1; i >= 0; i--)
        {
            ClearControls(control.Controls[i]);
        }

        if (!(control is TableCell))
        {
            if (control.GetType().GetProperty("SelectedItem") != null)
            {
                LiteralControl literal = new LiteralControl();
                control.Parent.Controls.Add(literal);
                try
                {
                    literal.Text =
                        (string)control.GetType().GetProperty("SelectedItem").
                            GetValue(control, null);
                }
                catch
                { }
                control.Parent.Controls.Remove(control);
            }
            else if (control.GetType().GetProperty("Text") != null)
            {
                LiteralControl literal = new LiteralControl();
                control.Parent.Controls.Add(literal);
                literal.Text =
                    (string)control.GetType().GetProperty("Text").
                        GetValue(control, null);
                control.Parent.Controls.Remove(control);
            }
        }
        return;
    }

导出为ex​​cel时如何使用ClearControl

protected void btnExport_Click(object sender, EventArgs e)
    {
        // Reference your own GridView here
        if (GridView1.Rows.Count > 65535)
        {
            //DisplayError("Export to Excel is not allowed" +
            //    "due to excessive number of rows.");
            return;
        }

        Response.Clear();
        Response.AddHeader("Content-Disposition", "attachment;filename=nameofexcelfile_" + DateTime.Now+".xls" );
        Response.Charset = "";

        // SetCacheability doesn't seem to make a difference (see update)
        Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

        Response.ContentType = "application/vnd.ms-excel";

        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

        // Replace all gridview controls with literals

        GridView1.PagerSettings.Visible = false;
        ClearControls(GridView1);

        System.Web.UI.HtmlControls.HtmlForm form
            = new System.Web.UI.HtmlControls.HtmlForm();
        Controls.Add(form);
        form.Controls.Add(GridView1GridView1);
        form.RenderControl(htmlWriter);
        Response.Write(stringWriter.ToString());
        Response.End();
    }

这将打印没有分页按钮的记录