2011-10-09 69 views
0

我有一些列的GridView。所有列绑定列,如:获取当前的GridView列值

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

最后一列是:

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

正如你看到的,有 “点击” 的一些方法..像:

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

随着我得到的代码(offcourse)我在单元格编号2中的选定行上有什么。我如何从同一行(并从单元格编号2)获得值按钮被单击而没有“selceted行”?例如:当我点击第2行上的按钮 - 我得到该行的单元格2。

这可能吗?

+0

被绑定到小区2什么数据字段? –

+0

@Lucasus - 订单号 – Oshrib

回答

1

如果你想在更清洁的方式来获取 '订单ID',你可以使用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(); 
     // ... 
    } 
} 
+0

太棒了。谢谢 ! – Oshrib

+0

如果我需要多个数据字段,我该怎么办?例如:orderId,电子邮件,用户名?我怎么写? – Oshrib

+0

我刚刚向您回答有问题的评论。 –