从数据库加载数据并在GridView中显示的最佳方式

时间:2016-07-28 07:07:28

标签: c# asp.net gridview postback viewstate

我是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" %>

这又有一个问题,就是在Postbacks之后,GridView没有任何东西可以显示。接下来我将结果保存到ViewState,在每个帖子上我都检索/更新了ViewState。

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

GridView代码段

 <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();
    }

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

当你在page_load

中使用IsPostback时,你需要做的就是绑定绑定gridview
 if(!IsPostBack)
{    var data = new AppsAuthData().GetAllUsers();
     ViewState["UserData"] = data;
     gridUsersInfo.DataSource = data;
     gridUsersInfo.DataBind();
}

听到一个例子:Asp.Net Bind Grid View

答案 2 :(得分:0)

在.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>
.px.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();
        }