[英]How to make textbox readonly in a gridview?
我有一个gridview,其中文本框仅在少数情况下应可编辑。.我尝试了以下代码,但无法解决该问题并使文本框不可编辑。
protected void GridView1_OnRowEditing(object sender, GridViewEditEventArgs e)
{
....
if (some condition)
{
..................
}
else(some condition)
{
.............
}
else if(some other)
{
TextBox itm = (GVEditRate.Rows[e.NewEditIndex].FindControl("TextBox1") as TextBox);
itm.Enabled = true;
TextBox prfc = (GVEditRate.Rows[e.NewEditIndex].FindControl("TextBox2") as TextBox);
prfc.Enabled = false;
TextBox anest = (GVEditRate.Rows[e.NewEditIndex].FindControl("TextBox3") as TextBox);
anest.Enabled = false;
}
您是否尝试过:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == DataControlRowState.Alternate)
{
//on you condition
TextBox txt = (TextBox)e.Row.FindControl("ControlID");
if(txt !=null)
{
txt.Attributes.Add("readonly", "readonly");
// txt.Attributes.Remove("readonly"); To remove readonly attribute
}
}
}
注释中,您可以在RowDataBound事件上执行以下代码
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == DataControlRowState.Alternate)
{
//on you condition
TextBox txt = (TextBox)e.Row.FindControl("ControlID");
txt.ReadOnly = true;
}
}
我更喜欢在网格列的页面中使用数据绑定表达式
<asp:TextBox runat="server" Enabled='<%# YourMethodThatReturnCondition(Eval("Field1"), Eval("Field2"), ...)%>' ></asp:TextBox>
我们的YourMethodThatReturnCondition是返回布尔值的方法
<asp:GridView ID="grdTaskDataCat1" OnRowCommand="grdTaskDataCat1_RowCommand" OnSorting="grdTaskDataCat1_Sorting" AutoGenerateColumns="false" ShowHeaderWhenEmpty="true" AllowSorting="true" Width="100%" DataKeyNames="ID" runat="server" OnRowDataBound="grdTaskDataCat1_RowDataBound">
<Columns> <asp:TemplateField HeaderText="Sr No" Visible="false"> <ItemTemplate> <asp:TextBox ID="txtId" Visible="false" ReadOnly Style="width: 30%" Text='<%# Bind("ID")%>' runat="server"></asp:TextBox> </ItemTemplate> </asp:TemplateField>
</Columns>
</asp:GridView>
在GridView的ROW数据绑定上
protected void grdTaskDataCat1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txt = (TextBox)e.Row.FindControl("txtTaskName");
if (txt.Text != "")
{
txt.Attributes.Add("readonly", "readonly");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.