我有一个ASP.Net数据绑定GridView,我想点击一行打开一个URL传递所选行的ID。 ID是数据库表中的一列,但我不想将其显示给用户。
如果我将ID列可见性设置为false,则不会使用数据填充列。即e.Row.Cells[0].Text
返回一个空字符串。
下面的代码工作正常,但我想使用ID列未显示。
在.aspx文件中:
<asp:GridView
id="GridViewTest"
runat="server"
DataSourceID="sqlSource"
AutoGenerateColumns="false"
OnRowDataBound="GridViewTest_RowDataBound"
>
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"/>
<asp:BoundField DataField="DisplayName" HeaderText="Name" />
</Columns>
</asp:GridView>
在.cs文件中:
protected void GridViewTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] = $"location.href = 'default.aspx?appID={e.Row.Cells[0].Text}'";
e.Row.Attributes["style"] = "cursor:pointer";
}
}
确保选择正确的单元格。例如,如果我显示了选择和编辑按钮,我必须得到第3个单元格:
txtbox.Text = e.Row.Cells[2].Text;
或者,您需要将ID字段转换为模板字段,从而创建可以找到的控件。
// get the label inside the ItemTemplate.
Label lbl = (Label)e.Row.Cells[0].FindControl("Label1");
// get the label's text and put it into a textbox.
txtbox.Text = lbl.Text;
为了解决这个问题,我将DataKeyNames属性设置为我想要使用的数据库表列的名称,在本例中为ID。
<asp:GridView
id="GridViewTest"
runat="server"
DataSourceID="sqlSource"
AutoGenerateColumns="false"
OnRowDataBound="GridViewAppInstallCount_RowDataBound"
DataKeyNames="ID"
>
<Columns>
<asp:BoundField DataField="DisplayName" HeaderText="Name" />
</Columns>
</asp:GridView>
使用此代码检索值:
protected void GridViewTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] = $"location.href = 'default.aspx?appID={GridViewTest.DataKeys[e.Row.RowIndex]["ID"]}'";
e.Row.Attributes["style"] = "cursor:pointer";
}
}