来自标签中gridview的ID

时间:2016-06-15 05:13:17

标签: asp.net gridview

我有一个gridview,其中有ID列..现在,当我点击该列时,我想在标签中显示该ID

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        ID = e.Row.Cells[0].Text;

        Label1.Text = "<b>Publisher Name  &nbsp;:&nbsp;&nbsp;   " + ID + "</b>";

    }

当我点击ID标签显示publisher name但我想从网格视图显示ID

我是怎么做的

1 个答案:

答案 0 :(得分:1)

您正在使用错误的事件。您应该在GridViewAutoGenerateSelectButton="True"中启用行选择并处理OnSelectedIndexChanged事件

代码背后:

public partial class GridViewSelectionExample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            this.Bind();
        }
    }

    private void Bind()
    {
        User user1 = new User { ID = 1, Name = "User 1" };
        User user2 = new User { ID = 2, Name = "User 2" };
        User user3 = new User { ID = 3, Name = "User 3" };

        GridView1.DataSource = new List<User> { user1, user2, user3 };
        GridView1.DataBind();
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string id = GridView1.SelectedRow.Cells[1].Text;
        lblCurrentID.Text = String.Format("The selected id is - {0}", id);
    }
}

<强> .ASPX:

<asp:GridView
    ID="GridView1"
    runat="server"
    AutoGenerateColumns="false" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AutoGenerateSelectButton="True">
    <Columns>
        <asp:BoundField DataField="ID" />
        <asp:BoundField DataField="Name" />
    </Columns>
</asp:GridView>
<asp:Label ID="lblCurrentID" runat="server"></asp:Label>