从Gridview中的超链接获取行

时间:2013-03-12 19:33:53

标签: asp.net gridview

我在asp.net gridview中有一个超链接字段,它在aspx文件中运行代码,比如

<asp:GridView ID="gvCoursesList" runat="server">
    <Columns>
        <asp:BoundField DataField="Course" HeaderText="Course">
        </asp:BoundField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lblSignup" runat="server" Text="Sign Up" OnClick= "lblSignup_Click" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

在我的代码隐藏文件中,我有以下功能:

    protected void lblSignup_Click(object sender, EventArgs e)
    {
    }

如何从此函数中检索第一列的值。 我想做点什么

string course = gvCoursesList.DataKeys[e.RowIndex].Value.ToString();

但它不起作用。还有其他想法吗?

4 个答案:

答案 0 :(得分:1)

<asp:GridView ID="gvCoursesList" runat="server" OnRowCommand="gvCoursesList_RowCommand">
<Columns>
    <asp:BoundField DataField="Course" HeaderText="Course">
    </asp:BoundField>
    <asp:TemplateField>
        <ItemTemplate>
            <asp:LinkButton ID="lblSignup" runat="server" Text="Sign Up" CommandName="SignUp" />
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

protected void gvCoursesList_RowCommand(object sender, GridViewRowCommandEventArgs e)
{
  if(e.CommandName=="SignUp")
  {
     string course = gvCoursesList.DataKeys[e.RowIndex].Value.ToString();
  }
}

答案 1 :(得分:1)

@jishnusaha应该是你应该采取的方法。这是另一种选择:http://forums.asp.net/p/1137287/1821091.aspx

protected void lblSignup_Click(object sender, EventArgs e)
{
    LinkButton btn = sender as LinkButton;
    GridViewRow row = btn.NamingContainer as GridViewRow;

    string course = gvCoursesList.DataKeys[row.RowIndex].Value.ToString();
}

答案 2 :(得分:0)

使用.cells.text获取值:

protected void lblSignup_Click(object sender, EventArgs e)
{
    GridViewRow row = gvCoursesList.rows[e.rowindex]
    string course = row.cells[cellIndex].text;
}

答案 3 :(得分:0)

感谢codingbiz。他的解决方案需要稍微调整一下,如下所示。

LinkButton btn = sender as LinkButton;
GridViewRow row = btn.NamingContainer as GridViewRow;
string course = row.Cells[0].Text;