问题
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