我是ASP.NET新手。我使用GridView。当我计算GridView的行时,它总是显示0。我在给代码。但是当我运行代码浏览器时,它会显示数据。怎么解决这个问题?
我的CS代码是:
protected void btnSend_OnClick(object sender, EventArgs e)
{
string MemberList= (ViewState["Memberlist"]).ToString();
List<PreparedEmail> preparedEmail = new List<PreparedEmail>();
Utility util = new Utility();
int count = 0;
int i1 = dlClients.Rows.Count; // it shows always 0
#region Send Invitation
foreach (GridViewRow mail in dlClients.Rows)
{
//some code here, It is never execute as dlClients.Rows shows 0
}
}
我的aspx代码是:
<asp:GridView ID="dlClients" EnableViewState="false" runat="server" AutoGenerateColumns="False" ClientIDMode="Static" GridLines="None" AllowPaging="false" CssClass="table table-bordered table-striped" OnPreRender="dlClients_PreRender" DataKeyNames="MemberId" PageSize="10" ShowHeader="true">
我的数据绑定代码:
Protected void dlClients_PreRender(object sender, EventArgs e)
{
List<CircleUser> memberList = new CircleUserBusinessLogic().GetAll();
dlClients.DataSource = memberList;
dlClients.DataBind();
//GridUpdatePanel.Update();
ViewState["Memberlist"] = memberList;
if (dlClients.Rows.Count > 0)
{
//Replace the <td> with <th> and adds the scope attribute
dlClients.UseAccessibleHeader = true;
//Adds the <thead> and <tbody> elements required for DataTables to work
dlClients.HeaderRow.TableSection = TableRowSection.TableHeader;
//Adds the <tfoot> element required for DataTables to work
dlClients.FooterRow.TableSection = TableRowSection.TableFooter;
}
}
答案 0 :(得分:5)
通常首先调用asp按钮单击事件,然后触发gridview预渲染。因此Gridview行数为0。
尝试在PageLoad方法或按钮单击中绑定gridview。
这里示例绑定...
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack )
{
DataTable dt = new DataTable();
dt = GetData();
dlClients.DataSource = dt;
dlClients.DataBind();
}
}
答案 1 :(得分:1)
在button_click
事件之前调用prerender
事件。这意味着,当按钮单击事件正在运行时,databind
尚未运行,因此GridView为空。要解决此问题,您可以在页面的load
事件中进行数据绑定。这是在点击事件之前调用的。
答案 2 :(得分:1)
在Button PreRender
事件中调用Gridview click
事件,如下所示:
protected void btnSend_OnClick(object sender, EventArgs e)
{
dlClients_PreRender(sender, args);
string MemberList = (ViewState["Memberlist"]).ToString();
List<PreparedEmail> preparedEmail = new List<PreparedEmail>();
Utility util = new Utility();
int count = 0;
int i1 = dlClients.Rows.Count;
foreach (GridViewRow mail in dlClients.Rows)
{
//some code here, It is never execute as dlClients.Rows shows 0
}
}
答案 3 :(得分:0)
EnableViewState = "true"
是一种将数据从一个页面传递到另一个页面的方法