【问题标题】:Get current GridView column value获取当前 GridView 列值
【发布时间】:2011-10-09 23:24:55
【问题描述】:

我有一些列的 GridView。所有列都是boundfield,如:

            <asp:BoundField DataField="orderId" HeaderText="orderId" 
            SortExpression="orderId"></asp:BoundField>

最后一列是:

                    <asp:LinkButton ID="LinkButton1" runat="server"    
  CommandName="" onclick="LinkButton1_Click" Text="Button"></asp:LinkButton>

如你所见,有一些方法的“onclick”..比如:

        lbltest.Text = gv_order.Rows[gv_order.SelectedIndex].Cells[2].Text;

使用该代码,我得到(offcourse)我在单元格 2 中选定行上的内容。如何从没有“选定行”的情况下单击按钮的同一行(以及单元格 2)获取值?示例:当我单击第 2 行上的按钮时 - 我得到该行的单元格 2。

这可能吗?

【问题讨论】:

  • 单元格2绑定了什么数据域?

标签: c# asp.net gridview


【解决方案1】:

如果您想以更干净的方式检索“orderid”,可以使用CommandNameCommandArgument 属性和OnRowCommand 事件,如下所示:

        <asp:GridView (...) OnRowCommand="Gv_RowCommand" (...)>

...

        <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select"
     CommandArgument='<%# Bind("orderId") %>' Text="Button"></asp:LinkButton>

在后面的代码中:

protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Select")
    {
         int selectedOrderId = Convert.ToInt32(e.CommandArgument);
         // ... 
    }
}

我希望这是你想做的。

编辑 - 我对您的评论的回答:

然后,它稍微复杂一些,并以某种方式使用“selectedRow”。在我自己的代码中,我使用了这种方法:

    <asp:GridView ID="gv1" (...) DataKeyNames="orderId,email,username"
         OnRowCommand="Gv_RowCommand" (...)>

            ...

    <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select"
       CommandArgument='<%# DataBinder.Eval(Container,"RowIndex") %>' Text="Button">
</asp:LinkButton>

在后面的代码中:

protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int selectedRowIndex = Convert.ToInt32(e.CommandArgument);
    if (e.CommandName == "Select")
    {
         int orderId = Convert.ToInt32(gv1.DataKeys[selectedRowIndex]["orderId"]);
         string email = gv1.DataKeys[selectedRowIndex]["email"].ToString();
         // ... 
    }
}

【讨论】:

  • 如果我需要多个数据字段,我该怎么办?示例:orderId、电子邮件、用户名?我该怎么写?
  • 我刚刚回复了你的评论。
  • 我对所有问题都很满意.. 我现在收到错误:关于索引大小的 System.ArgumentOutOfRangeException.. 我尝试更改大小但仍然收到错误
  • @Bside,哪个语句会抛出这个错误? index的值是多少?
  • @Bside,GridView 的 DataKeyNames 中是否列出了“txId”?此错误仅对“txId”显示?
猜你喜欢
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
  • 2021-05-07
  • 2010-11-26
相关资源
最近更新 更多