如何在网格视图中查找按钮



我的项目中有网格视图,并且该网格视图中有一个按钮。 我想根据 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.

单击此处查看我的屏幕

你必须在循环中使用[row]

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;
}
}
}            
}

不需要在 RowDataBound 事件中循环 GridView。当数据绑定到 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;
}
}
}

在你的代码中,一切看起来都非常好。这是查找控件的正确方法。只有一个建议,但不确定它是否有效,您可以更改键入按钮的方式

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

最新更新