我正在使用 gridview 控件并手动执行分页和排序。 分页的方法如下:
protected void gdvMainList_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gdvMainList.PageIndex = e.NewPageIndex;
gdvMainList.DataSource = dtConsentReleaseList;
gdvMainList.DataBind();
}
我有一个静态数据表,其中有一列 Id:
dtConsentReleaseList.Columns.Add("Id");
dtConsentReleaseList.Columns.Add("StartDate");
dtConsentReleaseList.Columns.Add("EndDate");
dtConsentReleaseList.Columns.Add("Contact");
我在 GridView 中分配数据键名称“Id”。 每行还有一个打印按钮。当我单击该按钮时,将执行此代码:
else if (e.CommandName == "New")
{
int selectedIndex = Convert.ToInt32(e.CommandArgument);
int consentReleaseId = Convert.ToInt32(gdvMainList.DataKeys[selectedIndex].Value);
string openReportScript = Utility.OpenReport(ResolveClientUrl("~/Reports/Consumer/ConsentReleaseReport.aspx?Id=" + consentReleaseId + "&ReportTitle=ConsentForRelease"));
ScriptManager.RegisterClientScriptBlock(upConsentRelease, upConsentRelease.GetType(), "Pop up", openReportScript, true);
}
但是当我更改页面并单击打印按钮时,此行出现异常:
int consentReleaseId = Convert.ToInt32(gdvMainList.DataKeys[selectedIndex].Value);
例外是:
Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index
我想我在分页方法中做错了什么。
请问有什么帮助吗?
您正在尝试根据任意 ID 而不是实际索引从数组中获取值。但你根本不需要这样做。您不需要将 ID 存储在
DataKeys
中,也不需要使用项目的索引来访问任何内容。只需从CommandArgument
中取出您的身份证即可。
<asp:ImageButton CommandName="New" CommandArgument='<%# Eval("Id") %>' ID="ibtnPrint" runat="server" ImageUrl="~/App_Themes/Default/images/print.png" />
然后在代码隐藏中:
int consentReleaseId = int.Parse(e.CommandArgument);
我的猜测是,您在代码隐藏中绑定了 gridview (可能是 page_load 事件),并且它不保存回发时的值。
此外,尝试将 Id 作为 CommandArgument 传递。据我所知,如果您有权访问所选记录的 Id,则根本不需要网格的行索引。 (GridView 默认将行索引作为 CommandArgument 传递)
在设置数据源并绑定gridview之前设置datakeyname。
此外,
string[] dk = new string[1] {"MyID"};
myGridView.DataKeyNames = dk;
myGridView.DataSource = ds;
myGridView.DataBind();