使用<asp:GridView></asp:GridView>
我试图显示数据库表的列。我想获取表的主键但显然不想显示它。我怎样才能做到这一点?
这是我的GridView
<asp:GridView ID="MyGrid" runat="server" BorderColor="#0066FF" AllowPaging="false" PageSize="5" AllowSorting="true" AutoGenerateColumns="false"
AutoGenerateEditButton="true" OnRowEditing="MyGrid_RowEditing" AutoGenerateDeleteButton="true" OnRowDeleting="MyGrid_RowDeleting"
OnRowDataBound="MyGrid_RowDataBound" EmptyDataText="No Value" BorderWidth="0px" BorderStyle="Solid">
<Columns>
<asp:BoundField DataField="PrimaryKey" HeaderText="UserId"/>
<asp:BoundField DataField="Column1" HeaderText="Column1" />
<asp:BoundField DataField="Column2" HeaderText="Column2" />
<asp:BoundField DataField="Column3" HeaderText="Column3" />
</Columns>
</asp:GridView>
我还尝试visible=false
隐藏主键,它隐藏了主键,但也没有获取其值,我想要这个值。
希望我的问题很明确。
答案 0 :(得分:6)
您需要在OnRowDataBound事件中设置Visible = false,这意味着您仍然可以访问数据,但不会在页面上显示。
<asp:GridView ID="MyGrid" runat="server" BorderColor="#0066FF"
AllowPaging="false" PageSize="5" AllowSorting="true"
AutoGenerateColumns="false" AutoGenerateEditButton="true"
OnRowEditing="MyGrid_RowEditing" AutoGenerateDeleteButton="true"
OnRowDeleting="MyGrid_RowDeleting"
OnRowDataBound="MyGrid_RowDataBound" EmptyDataText="No Value"
BorderWidth="0px" BorderStyle="Solid">
<Columns>
<asp:BoundField DataField="PrimaryKey" HeaderText="UserId"/>
<asp:BoundField DataField="Column1" HeaderText="Column1" />
<asp:BoundField DataField="Column2" HeaderText="Column2" />
<asp:BoundField DataField="Column3" HeaderText="Column3" />
</Columns>
</asp:GridView>
在Codebehind中:
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false;
}
答案 1 :(得分:2)
<asp:GridView ... DataKeyNames="PrimaryKey" />
答案 2 :(得分:1)
答案 3 :(得分:0)
<asp:BoundField DataField="PrimaryKey" visible="false" HeaderText="UserId"/>
获取主键
<asp:GridView ID="MyGrid" runat="server" BorderColor="#0066FF" DataKeyNames="PrimaryKey"
MyGrid.DataKeys[e.NewEditIndex].Value
OR
MyGrid.Rows[e.NewEditIndex].DataBoundItem
答案 4 :(得分:0)
如果要在GridView中按名称而不是其索引隐藏列。在创建DataTable或Dataset之后,您必须按名称查找列的索引,然后将索引保存在全局变量中,如ViewStae,Session等,然后在RowDataBound中调用它,如示例所示:
string headerName = "Id";
DataTable dt = .... ;
for (int i=0;i<dt.Columns.Count;i++)
{
if (dt.Columns[i].ColumnName == headerName)
{
ViewState["CellIndex"] = i;
}
}
... GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Footer)
{
int index = Convert.ToInt32(ViewState["CellIndex"]);
e.Row.Cells[index].Visible = false;
}
}