2011-12-29 90 views
0

我有這樣的GridView:GridView識別點擊行值?

<div class="content"> 
    <asp:GridView ID="DocumentGrid" runat="server" AutoGenerateColumns="False" OnRowCommand="DocumentGrid_RowCommand" > 
     <Columns> 
      <asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-Width="120px"/> 
      <asp:ButtonField HeaderText="Download Link" Text="Download"/> 
     </Columns> 
    </asp:GridView> 
</div> 

正如你所看到的,DocumentGrid_RowCommand被稱爲當「下載」按鈕被按下時,我怎樣才能找出的值是被點擊了該行的?

+0

我問過類似的問題在這裏一段時間回來。也許[這](http://stackoverflow.com/questions/8363202/in-c-how-can-i-reference-a-specific-product-record-based-on-a-button-thats-cl)將幫幫我。 – 2011-12-29 13:20:27

+0

or this http://stackoverflow.com/questions/5619630/getting-boundfield-value-in-gridview-row-command – 2011-12-29 13:37:10

回答

1

如果在GridView中有多個按鈕字段,請設置CommandName屬性。這樣我們可以確定在RowCommand事件中按下哪個按鈕。所以總是設置commandName屬性。

<Columns> 
<asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-Width="120px"/> 
<asp:ButtonField HeaderText="Download Link" Text="Download" CommandName="cmd"/> 
</Columns> 

RowCommand事件處理程序,GridViewCommandEventArgs.CommandArgument屬性返回其上按下的按鈕的行的索引。

protected void DocumentGrid_RowCommand(object sender, GridViewCommandEventArgs e) 
    { 
     if (e.CommandName == "cmd") 
     { 
      int index = int.Parse(e.CommandArgument.ToString()); 
      GridViewRow row = DocumentGrid.Rows[index]; 
      if (row.RowType == DataControlRowType.DataRow) 
      { 
       Response.Write(row.Cells[0].Text); 
      } 
     } 
    } 
1

如果設置這樣的標記,

 <Columns> 
      <asp:TemplateField HeaderText="Download"> 
       <ItemTemplate> 
        <asp:Button ID="btnDownload" CommandName="Download" CommandArgument='<%# Container.DataItemIndex %>' 
         runat="server" Text="Download" /> 
       </ItemTemplate> 
      </asp:TemplateField> 
     </Columns> 

在代碼隱藏,你可以檢查CommandArgument這樣的:

if (e.CommandName == "Download") 
{ 
    int index = Convert.ToInt32(e.CommandArgument); 
}