2013-09-24 71 views
3
Button btnAddrecord = (Button)sender; 
GridViewRow gvr =(GridViewRow)btnAddrecord.NamingContainer; 
if (btnAddrecord.CommandName == "onAddMaterial") 
+1

請提供該問題的更多細節? –

回答

4

定義按鈕,在你的網格視圖的標記和CommandName值分配給該按鈕,像這樣:

<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server" 
     OnRowCommand="GridView1_RowCommand"> 
    <Columns> 
     <asp:TemplateField HeaderText="Add Record"> 
      <ItemTemplate> 
       <asp:Button ID="btnAddRecord" 
          CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" 
          CommandName="AddRecord" runat="server" Text="Add" /> 
      </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

現在,在您的代碼隱藏,你可以處理OnRowCommand事件和AddRecord命令,就像這樣:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    if (e.CommandName == "AddRecord") 
    { 
     // Get index of row passed as command argument 
     int index = Convert.ToInt32(e.CommandArgument.ToString()); 

     // Your logic here 
    } 
} 
+0

這對我來說只是好奇「<%#((GridViewRow)Container).RowIndex%>」語法的工作原理。 – JoeManiaci

+1

@JoeManiaci - <%#'被稱爲嵌入式代碼塊語法,在這種特殊的語法中,它將綁定到GridView的每一行的索引(通過RowIndex屬性)進行數據綁定控制。然後,當用戶單擊特定行中的Add按鈕時,CommandName用於確定用戶想要執行的命令(在單個網格視圖行中可能有多個命令),最後使用CommandArgument獲取用戶點擊的確切行的索引。這基本上允許您獲取用戶單擊的行的上下文。 –

+0

太棒了,謝謝。 – JoeManiaci

0

確定公司運作的按鈕命令名稱..裏面的GridView
2.然後

if e.commandname="yourcommandname" 
{ 
//your code.. 
} 
0
 <!--We use onrowcommand for getting the selected row --> 
<asp:GridView runat="server" ID="gvTest" AutoGenerateColumns="False" OnRowCommand="gvTest_OnRowCommand" > 
      <Columns> 
       <asp:TemplateField HeaderText="BookId" > 
       <ItemTemplate> 
        <asp:Label runat="server" ID="lblBookId" Text='<%# Bind("[BookId]") %>'></asp:Label> 
       </ItemTemplate> 
        <EditItemTemplate> 
         <asp:TextBox runat="server" ID="txtBookId" Text='<%# Bind("[BookId]") %>'></asp:TextBox> 
        </EditItemTemplate> 
       </asp:TemplateField> 
      </Columns> 
      </asp:TemplateField> 
       <asp:TemplateField HeaderText="Options"> 
        <ItemTemplate> 
         <asp:Button runat="server" ID="btnDelete" CommandArgument="<%# Container.DisplayIndex %>" CommandName="IsDelete" Text="Delete"></asp:Button> 
        </ItemTemplate> 
       </asp:TemplateField> 

//Code Behind 

protected void gvTest_OnRowCommand(object sender, GridViewCommandEventArgs e) 
    { 
     try 
     { 
      //getting rowindex which we have selected by using CommandArgument 

       int rowindex = Convert.ToInt32(e.CommandArgument); 


        if (e.CommandName == "IsDelete") 
        { 

         int bkid = gvTest.Rows[rowindex].Cells[0].FindControl("BookId"); 

         //call a method to delete book using the bkid 

        } 

     } 
     catch (Exception ex) 
     { 

      Response.Write(ex); 
     } 
    }