1

我有一个 gridView 。在后面的代码中,我想获取 Id 和 Name

<asp:GridView ID="GridViewCategory" runat="server" 
        OnSelectedIndexChanged="GridViewCategory_SelectedIndexChanged"
         OnPageIndexChanging="GridViewCategory_PageIndexChanging"
          AllowPaging="True" DataKeyNames="Id"
         CellPadding="4" ForeColor="#333333" GridLines="None"
        >
      <Columns>
                <asp:BoundField DataField="Id" HeaderText="Идент. номер" ItemStyle-Wrap="false" ItemStyle-Width="20%" />
                <asp:BoundField DataField="Name" HeaderText="ALl name For" ItemStyle-Wrap="false" ItemStyle-Width="60%" />
                <asp:CommandField SelectText="Избери" ShowSelectButton="True" />
            </Columns>

我通过这个得到 ID:

protected void GridViewCategory_SelectedIndexChanged(object sender, EventArgs e)
        {

            int  abv = Convert.ToInt32(GridViewCategory.SelectedValue);
            //Label labelName = (Label)GridViewCategory.SelectedRow.FindControl("Name"); this is not working I think because it is  BoundField And rows don't  have Id only DataField 

        }

但是如何获得这个 ID 的名字

4

1 回答 1

0

您可以将 Name 添加为另一个 datakeyname

<asp:GridView ID="GridViewCategory" runat="server" 
    OnSelectedIndexChanged="GridViewCategory_SelectedIndexChanged"
     OnPageIndexChanging="GridViewCategory_PageIndexChanging"
      AllowPaging="True" DataKeyNames="Id, Name"
     CellPadding="4" ForeColor="#333333" GridLines="None"
    >
  <Columns>
            <asp:BoundField DataField="Id" HeaderText="Идент. номер" ItemStyle-Wrap="false" ItemStyle-Width="20%" />
            <asp:BoundField DataField="Name" HeaderText="ALl name For" ItemStyle-Wrap="false" ItemStyle-Width="60%" />
            <asp:CommandField SelectText="Избери" ShowSelectButton="True" />
        </Columns>

然后在你的代码后面:

protected void GridViewCategory_SelectedIndexChanged(object sender, EventArgs e)
    {

        int  index = GridViewCategory.SelectedIndex;
        int abv =  Convert.ToInt32(this.GridViewCategory.DataKeys[index]["Id"]);
        string name = this.GridViewCategory.DataKeys[index]["Name"].ToString();

    }

希望这可以帮助

于 2013-06-09T13:16:13.603 回答