2017-08-06 80 views
0

我在我的項目中有gridview,並且在gridview中有一個按鈕。 我想根據GridView的單元格的值如何在gridview中查找按鈕

下面

改變該按鈕的屬性是我的GridView控件與按鈕

<div class="row"> 
    <div class="col-md-12"> 
     <h1 style="color:red" id="payDetailH" runat="server" visible="false">Payment Details</h1> 
     <br /> 
     <asp:Panel ID="Panel2" runat="server" ScrollBars="Auto"> 
     <asp:GridView ID="gvPayemenDetailNew" CssClass="table table-hover" GridLines="None" runat="server" 
      OnRowCommand="gvPayemenDetailNew_RowCommand" OnRowDataBound="gvPayemenDetailNew_RowDataBound" > 
      <Columns> 
       <asp:TemplateField> 
        <ItemTemplate> 
         <asp:Button ID="btnGenNew" runat="server" CommandName="GJobID" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="Ceate Job" CssClass="btn" Enabled="False" /> 
        </ItemTemplate> 
       </asp:TemplateField> 
      </Columns> 
      <HeaderStyle Height="50px" HorizontalAlign="Center" VerticalAlign="Middle" /> 
     </asp:GridView> 
     </asp:Panel> 
     </div> 
</div> 

,這背後是

protected void gvPayemenDetailNew_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    foreach (GridViewRow row in gvPayemenDetailNew.Rows) 
    { 
     if (row.RowType == DataControlRowType.DataRow) 
     { 
      Button btn = e.Row.FindControl("btnGenNew") as Button; 
      if (PayStatus == "Approved") 
      { 
       btn.Enabled = true; 
      } 
     } 
    }    
} 

我得到這個錯誤我的代碼

System.NullReferenceException: Object reference not set to an instance of an object. 

click here to see my screens

回答

0

必須使用循環[行]

protected void gvPayemenDetailNew_RowDataBound(object sender, 
GridViewRowEventArgs e) 
{ 
foreach (GridViewRow row in gvPayemenDetailNew.Rows) 
{ 
    if (row.RowType == DataControlRowType.DataRow) 
    { 
     Button btn = row.FindControl("btnGenNew") as Button; 
     if (PayStatus == "Approved") 
     { 
      btn.Enabled = true; 
     } 
    } 
}    
} 
+0

謝謝主席先生及其工作 –

0

一切看起來真的很不錯在你的代碼。這是找到控件的正確方法。只是一個建議,但不知道其去工作,你可以改變你的類型強制轉換按鈕

Button btn = (Button)e.Row.FindControl("btnGenNew"); 
1

你並不需要循環在GridView的RowDataBound事件的方式。當數據綁定到GridView時,它已經在執行每行。在循環中,您可以根據最後一行值設置所有按鈕,而不是每行。

所以這應該是正確的方法,假設PayStatus是綁定到GridView的數據集中的一列。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    //check if the row is a datarow 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     //cast the row back to a datarowview 
     DataRowView row = e.Row.DataItem as DataRowView; 

     //find the button with findcontrol 
     Button btn = e.Row.FindControl("btnGenNew") as Button; 

     //use the paystatus of the current row to enable the button 
     if (row["PayStatus"].ToString() == "Approved") 
     { 
      btn.Enabled = true; 
     } 
    } 
} 
+0

感謝您的答覆先生,但是我的問題已經解決了 –

+0

沒問題。但是儘量避免在rowdatabound事件中循環gridview。 – VDWWD