Microsoft . 技术之路...

—— 专注于微软技术, 分享是快乐的源泉......
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

如何控制GridView单元格是否可编辑?

Posted on 2007-07-23 14:49  赣江源  阅读(1909)  评论(0编辑  收藏  举报

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