如果GridView的单元格是否需要编辑是根据判断某个状态值来决定时,可以在GridView 的 RowDataBound 事件中做判断并设置编辑按钮是否显示。代码如下:
*.aspx.cs
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView oRow;
LinkButton olinkButton;
if (e.Row.RowType == DataControlRowType.DataRow)
{
oRow = (DataRowView)e.Row.DataItem;
if (oRow != null)
{
//如果IsEdit字段值为false时,则将编辑按钮设置为隐藏
if (bool.Parse(oRow["IsEdit"].ToString()) == false)
{
//查找编辑按钮
olinkButton = FindCommandFieldButton(e.Row.Cells[0], "Edit") ;
if (olinkButton != null)
{
olinkButton.Visible = false; //隐藏按钮
}
}
}
}
}
/// <summary>
/// 查找指定 CommandName 的按钮
/// </summary>
private LinkButton FindCommandFieldButton(DataControlFieldCell cell, string sCommandName)
{
try
{
LinkButton olinkButton;
foreach (Control oControl in cell.Controls)
{
if (oControl.GetType() == typeof(System.Web.UI.WebControls.LinkButton))
{
olinkButton = (LinkButton)oControl;
if (sCommandName.ToUpper() == olinkButton.CommandName.ToUpper())
{
return olinkButton;
}
}
}
return olinkButton;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
{
DataRowView oRow;
LinkButton olinkButton;
if (e.Row.RowType == DataControlRowType.DataRow)
{
oRow = (DataRowView)e.Row.DataItem;
if (oRow != null)
{
//如果IsEdit字段值为false时,则将编辑按钮设置为隐藏
if (bool.Parse(oRow["IsEdit"].ToString()) == false)
{
//查找编辑按钮
olinkButton = FindCommandFieldButton(e.Row.Cells[0], "Edit") ;
if (olinkButton != null)
{
olinkButton.Visible = false; //隐藏按钮
}
}
}
}
}
/// <summary>
/// 查找指定 CommandName 的按钮
/// </summary>
private LinkButton FindCommandFieldButton(DataControlFieldCell cell, string sCommandName)
{
try
{
LinkButton olinkButton;
foreach (Control oControl in cell.Controls)
{
if (oControl.GetType() == typeof(System.Web.UI.WebControls.LinkButton))
{
olinkButton = (LinkButton)oControl;
if (sCommandName.ToUpper() == olinkButton.CommandName.ToUpper())
{
return olinkButton;
}
}
}
return olinkButton;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}