GridView template Column conditionally set to readonly

落爺英雄遲暮 提交于 2020-01-15 03:39:08

问题


Is there a way to set a Template Column on a GridView to readonly from code behind. Like if test for Admin=true make readonly= false else readonly = true?


回答1:


There is no direct way to set the GridView column to readonly. But You can set the controls to readonly that are in that column in the RowDataBound event of your GridView. e.g.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == DataControlRowState.Alternate)
    {
        TextBox txt = (TextBox)e.Row.FindControl("ControlID");
        txt.ReadOnly = true;
    }
}



回答2:


I find Muhammad Akhtar's answer is almost spot on except I need to change the if clause slightly in my case to cover all the conditions. My if clause is as follows.

if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit || 
    (e.Row.RowState & DataControlRowState.Alternate) == DataControlRowState.Alternate)

I didn't find any problem with the original one until I have a special value of e.Row.RowState as "Alternate | Edit", which make

(e.Row.RowState == DataControlRowState.Edit || 
 e.Row.RowState == DataControlRowState.Alternate) == false

Nevertheless, I should thank Muhammad Akhtar for pointing me towards the right direction.

Here is my complete code:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit || (e.Row.RowState & DataControlRowState.Alternate) == DataControlRowState.Alternate)
   {
      TextBox txt = (TextBox)e.Row.FindControl("ControlID");
      txt.ReadOnly = true;
   }
}

PS: In order to make DropDownList readonly, you need to disable it in its OnDataBound event:

protected void DropDownList1_DataBound(object sender, EventArgs e)
{
    ((DropDownList)sender).Enabled = false;
}



回答3:


Yes, tap into ItemDataBound event, and for each row, either use a readonly control and an edit control and show/hide the right control for the job, or alternatively disable the edit control. There's no global readonly setting for templates.

HTH.



来源:https://stackoverflow.com/questions/5897985/gridview-template-column-conditionally-set-to-readonly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!