【问题标题】:Best way to load data from DB and show in GridView从数据库加载数据并在 GridView 中显示的最佳方式
【发布时间】:2016-12-02 10:18:04
【问题描述】:

我是 ASP.Net 世界的新手,对如何处理以下场景感到困惑。

在我的应用程序中,我必须在页面加载时从数据库中获取数据并将其显示在 GridView 中。该表目前有大约 1000 条记录,大约 7 列。但数据将继续增长。

这是我如何将数据绑定到网格的代码。

 protected void Page_Load(object sender, EventArgs e)
 {
     var data = new AppsAuthData().GetAllUsers();
     gridUsersInfo.DataSource = data;
     gridUsersInfo.DataBind();
 }

我开始知道,在上面的每个帖子中,上面的代码都会被执行(这显然不好)。所以我在函数的开头添加了以下内容

if (IsPostBack)
     return;
var data = new AppsAuthData().GetAllUsers();
gridUsersInfo.DataSource = data;
gridUsersInfo.DataBind();

页面标记

<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeBehind="RemoveUsers.aspx.cs" Inherits="AppsAuth.Authencations.RemoveUsers" %>

这又有一个问题,即在回发之后,GridView 没有什么可显示的。所以接下来我将结果保存到 ViewState 中,并且在每次回帖时我都在检索/更新 ViewState。

但由于在某些情况下数据可能非常庞大,那么处理此类问题的最佳选择是什么?

GridView sn-p

 <asp:GridView ID="gridUsersInfo" runat="server" Width="100%" ForeColor="#333333" AllowPaging="True"
        AllowSorting="True" AutoGenerateColumns="false" OnSorting="UserInfo_Sorting" OnRowEditing="gridUsersInfo_RowEditing"
        OnPageIndexChanging="gridUsersInfo_PageIndexChanging" AutoGenerateEditButton="True">
 >    <Columns>
            <asp:BoundField DataField="USER_ID" ReadOnly="True" HeaderText="ID" SortExpression="USER_ID" />
            <asp:BoundField DataField="USER_NAME" ReadOnly="False" HeaderText="User Name" SortExpression="USER_NAME" />
        </Columns>
    </asp:GridView>

protected void gridUsersInfo_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gridUsersInfo.PageIndex = e.NewPageIndex;
        gridUsersInfo.DataBind();
    }

【问题讨论】:

  • 尝试在页面加载时将您的网格绑定代码保留在 !Ispostback
  • 通常不需要手动处理 ViewState 以在每次回发时重新加载网格。这似乎是您的 ASPX 标记或 ViewState 的常规设置的问题。请添加您的 ASPX 页面的标记。还要使用实际代码更新您的代码,否则有些人会在没有阅读您所有问题的情况下回答
  • @Steve 请查看更新后的问题(带有页面标记)
  • 检查您是否有某种EnableViewState 和相关的ViewStateMode 属性设置为非默认值
  • @Steve 我没有更改任何默认设置,调试器显示 EnableViewState = true 而 ViewStateMode = inherits

标签: c# asp.net gridview postback viewstate


【解决方案1】:

而不是将所有内容都放在 PageLoad 上。您可以放置​​一个按钮并编写代码以在该按钮的单击事件中填充 GridView。

使用启用分页的 asp.net 控件 Gridview 将为您完成此操作。

检查以下示例:

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
    OnPageIndexChanging="OnPageIndexChanging" PageSize="10">
    <Columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="CustomerID" HeaderText="Customer ID" />
        <asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
        <asp:BoundField ItemStyle-Width="150px" DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>

代码隐藏

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}

private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, ContactName, City, Country FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}

实现分页

当页面在 GridView 内发生更改时,将调用事件处理程序。 被点击的页面的 PageIndex 的值存在于 GridViewPageEventArgs 对象的 NewPageIndex 属性中,它被设置为 GridView 的 PageIndex 属性,然后通过调用 BindGrid 函数再次填充 GridView。

protected void OnPaging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    GridView1.DataBind();
}

来源:http://www.aspsnippets.com/Articles/Paging-in-ASPNet-GridView-Example.aspx

【讨论】:

  • 使用上面的代码当我导航到 GridView 的下一页或上一页时,我在网格上看不到任何内容,因为回发后网格的 DataSource 变为空(即使 EnableViewState 属性在我看到时似乎为真)调试器)
【解决方案2】:

你要做的就是在page_load中的!IsPostback时绑定绑定gridview

 if(!IsPostBack)
{    var data = new AppsAuthData().GetAllUsers();
     ViewState["UserData"] = data;
     gridUsersInfo.DataSource = data;
     gridUsersInfo.DataBind();
}

举个例子:Asp.Net Bind Grid View

【讨论】:

    【解决方案3】:

    在 .aspx 文件中

    <form runat="server" onload="Page_Load">
      <asp:GridView runat="server" ID="gridEvent" AutoGenerateColumns="False" BackColor="White"  
            BorderStyle="None" BorderWidth="0px" class="table mb-0"  
            > 
            <RowStyle BackColor="White" /> 
            <Columns>
                <asp:BoundField DataField="EventId" HeaderText="#" />
                <asp:BoundField DataField="Title" HeaderText="Event Title" />
                <asp:BoundField DataField="EventDate" HeaderText="Event Date" />
                <asp:BoundField DataField="Location" HeaderText="Venue" />
                <asp:BoundField DataField="RegisteredUsers" HeaderText="Registred User(s)" />
                <asp:CommandField ShowEditButton="True" /> 
                <asp:CommandField ShowDeleteButton="True" />
    
            </Columns>
            <FooterStyle BackColor="#99CCCC" ForeColor="#003399" /> 
            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" /> 
            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" /> 
            <HeaderStyle BackColor="#FBFBFB" Font-Bold="True" ForeColor="#5A6169" /> 
      </asp:GridView>
     </form>
    

    在 .aspx.designer.cs 中

    public partial class Default
        {
            /// <summary>
            /// txtLocation control.
            /// </summary>
            /// <remarks>
            /// Auto-generated field.
            /// To modify move field declaration from designer file to code-behind file.
            /// </remarks>
            protected global::System.Web.UI.WebControls.GridView gridEvent;
        }
    

    在 .aspx.cs 文件中

     protected void Page_Load(object sender, EventArgs e)
            {
                if (!this.IsPostBack)
                {
                    // Enable the GridView paging option and  
                    // specify the page size. 
                    gridEvent.AllowPaging = true;
                    gridEvent.PageSize = 15;
    
                    // Initialize the sorting expression. 
                    ViewState["SortExpression"] = "EventId ASC";
                    // Enable the GridView sorting option. 
                    gridEvent.AllowSorting = true;
                    BindGrid();
                }
            }
            private void BindGrid()
            {
                // Get the connection string from Web.config.
        // When we use Using statement,  
        // we don't need to explicitly dispose the object in the code,  
        // the using statement takes care of it. 
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConn"].ToString()))
                {
                    // Create a DataSet object. 
                    DataSet dsPerson = new DataSet();
    
    
                    // Create a SELECT query. 
                    string strSelectCmd = "SELECT * FROM EventsList";
    
    
                    // Create a SqlDataAdapter object 
                    // SqlDataAdapter represents a set of data commands and a  
                    // database connection that are used to fill the DataSet and  
                    // update a SQL Server database.  
                    SqlDataAdapter da = new SqlDataAdapter(strSelectCmd, conn);
    
    
                    // Open the connection 
                    conn.Open();
    
    
                    // Fill the DataTable named "Person" in DataSet with the rows 
                    // returned by the query.new n 
                    da.Fill(dsPerson, "EventsList");
    
    
                    // Get the DataView from Person DataTable. 
                    DataView dvPerson = dsPerson.Tables["EventsList"].DefaultView;
    
    
                    // Set the sort column and sort order. 
                    dvPerson.Sort = ViewState["SortExpression"].ToString();
    
    
                    // Bind the GridView control. 
                    gridEvent.DataSource = dvPerson;
                    gridEvent.DataBind();
                }
            }
            //Implementing Pagination
            protected void OnPaging(object sender, GridViewPageEventArgs e)
            {
                gridEvent.PageIndex = e.NewPageIndex;
                gridEvent.DataBind();
            }
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多