【发布时间】:2011-01-19 15:58:20
【问题描述】:
我在尝试向网格中添加按钮时遇到问题。我的 GridView 首先在 PageLoad 事件中加载数据。
然后,我将获取每行第一个单元格中的数据,并创建一个链接到 URL 的按钮。要获取 URL,我必须使用第一个单元格中的数据作为参数运行查询。起初我是在 RowDataBound 事件中执行此操作的,但是为每一行都点击该查询会使其非常慢。
所以我决定添加一个按钮,该按钮仅在您单击该按钮时才检索 URL。
这是我的 GridView:
<asp:GridView ID="gvResults" runat="server"
OnRowDataBound="gvResults_RowDataBound"
OnRowCommand="gvResults_RowCommand">
</asp:GridView>
还有我的代码:
protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
LinkButton lb = new LinkButton();
lb.CommandArgument = e.Row.Cells[0].Text;
lb.CommandName = "NumClick";
lb.Text = e.Row.Cells[0].Text;
e.Row.Cells[0].Controls.Add((Control)lb);
}
}
protected void gvResults_RowCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName.ToLower())
{
case "numclick":
string url = GetUrl(e.CommandArgument.ToString());
Response.Redirect(url);
break;
default:
break;
}
}
网格生成良好,按钮被添加到每一行的网格中。但是当我点击它时,不会触发 RowCommand 事件,并且页面只是刷新。
有谁知道问题出在哪里?
【问题讨论】:
-
在将其添加到 Cell 之前,我会将 ID 关联到 linkButton。