[英]Add Event on specific control in the gridview
I have a scenario, where i need to attach an event (textchanged) to a textbox. 我有一个场景,我需要将一个事件(textchanged)附加到文本框。 It should only trigger, if the code is "code2".
如果代码是“code2”,它应该只触发。 Please check the below code ;
请检查以下代码; The
value_TextChanged
doesn't get triggered: value_TextChanged
不会被触发:
<asp:GridView runat="server" ID="gv1" AutoGenerateColumns="false"
onrowcreated="gv1_RowCreated1" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="code" Text='<%# Bind("[code]") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" ID="val" Text='<%# Bind("[value]") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}
void DataBind()
{
DataTable dt = new DataTable();
dt.TableName = "tb1";
dt.Columns.Add("code");
dt.Columns.Add("value");
dt.Rows.Add("code1", "Red");
dt.Rows.Add("code2", "Green");
dt.Rows.Add("code3", "Blue");
gv1.DataSource = dt;
gv1.DataBind();
}
protected void gv1_RowCreated1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string code = (String)DataBinder.Eval(e.Row.DataItem, "code");
TextBox value = (TextBox)e.Row.FindControl("val");
if (code == "code2")
{
value.AutoPostBack = true;
value.TextChanged += new EventHandler(value_TextChanged);
}
}
}
void value_TextChanged(object sender, EventArgs e)
{
throw new NotImplementedException();
}
To trigger TextChange you need to add AutoPostBack="true"
in your Markup; 要触发TextChange,您需要在标记中添加
AutoPostBack="true"
; For attaching an event with TextChange you need not to depend gv1_RowCreated
that also you can specify in the markup. 要使用TextChange附加事件,您无需依赖
gv1_RowCreated
,也可以在标记中指定。
<asp:TextBox AutoPostBack="true" OnTextChanged="value_TextChanged"
runat="server" ID="val" Text="" ></asp:TextBox>
Please note one more thing, the event will trigger when the textBox loss its focus
请注意另外一件事,当textBox失去焦点时,事件将触发
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.