[英]How to Enable or Disable Text Box in GridView using C#
我希望能夠啟用/禁用gridview內的文本框。 我有case語句,在case語句中當Case = 1
我想在gridview中禁用一個名為txtType
。 這是我的代碼:
SqlDataAdapter da = new SqlDataAdapter(@"select * from my table ", con);
DataTable dtTable = new DataTable();
da.SelectCommand.Parameters.AddWithValue("@RSP_SET_SK", (RSP_SET_SK));
da.Fill(dtTable);
GridView1.DataSource = dtTable.DefaultView;
GridView1.DataBind();
DataRow dtTable_row = dtTable.Rows[0];
if (dtTable.Rows.Count > 0)
{
DDL_TYPE.SelectedValue = dtTable_row.Field<string>("TYPE").ToString();
ddlPr.SelectedValue = dtTable_row.Field<Int32>("ID").ToString();
}
DataRow row1 = dtTable.Rows[0];
int temp = Convert.ToInt32(row1["STATUS"]);
switch (temp)
{
case 1:
lblStatus.Text = temp + " - Initial Test.";
break;
}
由於它在gridview中,因此您將需要使用它。
GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
string type = ((TextBox).gvr.FindControl("txtType"));
然后禁用或啟用即可使用。
type.Enabled = true;
我希望這給您大致的思路。
編輯:您可能需要使用一個foreach循環。
foreach(GridViewRow gvr in GridView1.Rows)
{
string type = ((TextBox).gvr.FindControl("txtType"));
type.Enabled = true/false;
}
我應該想象這樣做。 我確實經常在我的一個應用程序中使用此foreach。
編輯2:
我只是意識到我把一段不應該的時期。 我的錯。 所以應該是這樣。
string type = ((TextBox)gvr.FindControl("txtType"));
要么
TextBox type = ((TextBox)gvr.FindControl("txtType"));
或者您可以像這樣直接啟用它。
((TextBox)gvr.FindControl("txtType")).Enabled = true/false;
您應該在RowDataBound Event中執行此操作。 下面的鏈接提供了示例代碼,可以為您提供幫助。
您可以在RowDataBound
事件中執行此操作。 首先,請確保您在aspx代碼中設置了OnRowDataBound
屬性,如下所示:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
</asp:GridView>
然后在代碼后面添加以下內容:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView data = (DataRowView)e.Row.DataItem;
TextBox txtType = (TextBox)e.Row.FindControl("txtType");
int status = Convert.ToInt32(data["STATUS"]);
if (status == 1)
{
txtType.Enabled = false;
}
}
}
a TextBox into a GridView
<asp:GridView ID="mygrid" runat="server">
<Columns>
<asp:TemplateField meta:resourcekey="TemplateFieldResource4">
<ItemTemplate>
<asp:TextBox ID="mytextBoxID" runat="server" Text="0,00" Enabled="false" />
</ItemTemplate>
<HeaderStyle Width="10%" HorizontalAlign="Right"/>
<ItemStyle HorizontalAlign="Right" />
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void any_Click(object sender, EventArgs e) {
foreach (GridViewRow gvr in gvData.Rows)
((TextBox)gvr.FindControl("mytextBoxID")).Enabled = true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.