C# 如何在gridview中查找按钮
我的项目中有gridview,gridview中有一个按钮。 我想根据gridview单元格值更改该按钮的属性 下面是我的gridview和按钮C# 如何在gridview中查找按钮,c#,asp.net,gridview,C#,Asp.net,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> &
<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>
我犯了这个错误
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;
}
}
}
}
代码中的一切看起来都很好。这是查找控件的正确方法。只有一个建议,但不确定它是否会起作用,你可以改变你打字的方式
Button btn = (Button)e.Row.FindControl("btnGenNew");
您不需要在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;
}
}
}
谢谢你的回复,先生,但是我的问题已经解决了。但是尽量避免在rowdatabound事件中循环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;
}
}
}