Reputation: 7611
I have a GridView which is populated from a database, and includes a textbox. Through the code behind, I want to subscribe the textbox on each row to a certain event, but only if a field of the row matches some if statement.
So I have the following:
protected void grdRates_RowDataBound(object sender, GridViewRowEventArgs e)
{
TextBox txt = (TextBox)e.Row.FindControl("txtValue");
DataRowView dataView = (DataRowView)e.Row.DataItem;
if ((bool)dataView["isAuto"])
{
txt.AutoPostBack = true;
txt.TextChanged += new EventHandler(txt_TextChanged);
}
}
protected void txt_TextChanged(object sender, EventArgs e)
{
//Other stuff here
}
The problem is, the text changed event never fires - the AutoPostBack property is being set, as the page posts back when they move out of the TextBox, but the text changed event does not fire. Am I missing something here?
Upvotes: 1
Views: 1552
Reputation: 23084
You should change the implementation so that you are not adding an event handler at the time of data binding, which will get you in all sorts of problems with the page lifecycle.
Instead, you could bind the AutoPostBack property declaratively and just set the event handler there as well.
<asp:TextBox ID="SomeInput" runat="server" ...
AutoPostBack='<%# (bool)Eval("IsAuto")'
OnTextChanged="SomeInput_TextChanged" />
The event will only fire automatically (i.e. when the input loses focus) when IsAuto == true, but it may still fire when the user clicks another button in the same row and the text in the input was changed. So you need an extra check in the event handler:
protected void SomeInput_TextChanged(object sender, EventArgs e)
{
TextBox input = (TextBox)sender;
if(input.AutoPostBack)
{
// Other stuff here
}
}
Notice that by declaratively binding we need to worry less about page life cycle, and we can use the bound property of the input to check against in the event handler.
Upvotes: 1