3

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?

Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191
BillTetrault
  • 213
  • 2
  • 6
  • 18

3 Answers3

5

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;
}
Simon Martin
  • 4,203
  • 7
  • 56
  • 93
yangli.liy
  • 101
  • 3
  • 5
4

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;
    }
}
Mykola
  • 3,343
  • 6
  • 23
  • 39
Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191
0

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.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257