How can I make a TextBox in a GridView not fire TextChanged when SelectedIndexChanged is fired?
I have a TextBox
in a TemplateField
in a GridView
that is supposed to show a checkmark after its TextChanged
event.
I also made the GridView
row selectable. If I select a row, the entire GridView
rebinds and fires the TextChanged
event for all TextBoxes
in the GridView
. This, of course, displays all the checkmarks.
I don't want to display the checkmarks on any rows the user did not change. I think the best wa开发者_运维百科y to do this is to prevent (unattach?) the TextChanged
event unless the user changes the text value.
Any suggestions?
I'm not sure if i've understood your problem actually because you haven't provided any source-code, but i try to give an answer anyway.
There are several options to avoid this behaviour:
- set the TextBox'
AutoPostback
-Property totrue
. On this way the TextChanged-Event will occur directly after the user entered something into the Textbox and presses Enter or leaves the Textbox' focus - You should hide the CheckMarks by default(
Visible="false"
) - You must not rebind the GridView
OnSelectedIndexChanging
but only set it'sSelectedIndex
toe.NewSelectedIndex
. On this way the Text of the Textboxes which was already been changed by the user will not be overwritten from the old db-values
Here's a simple example to demontrate what i mean:
<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" AutoGenerateSelectButton="true" OnSelectedIndexChanging="GridSelecting" OnRowDataBound="GridRowDataBound" >
<SelectedRowStyle BackColor="LightBlue" />
<columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckMark" Checked="true" Enabled="false" visible="false" runat="server" />
<asp:TextBox ID="Textbox1" runat="server" AutoPostBack="false" OnTextChanged="TextChanged"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:gridview>
Codebehind:
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack) {
BindGrid();
}
}
private void BindGrid()
{
DataTable source = new DataTable();
source.Columns.Add(new DataColumn("Value", typeof(string)));
DataRow row = source.NewRow();
row["Value"] = "A";
source.Rows.Add(row);
row = source.NewRow();
row["Value"] = "B";
source.Rows.Add(row);
row = source.NewRow();
row["Value"] = "C";
source.Rows.Add(row);
this.GridView1.DataSource = source;
this.GridView1.DataBind();
}
protected void TextChanged(object sender, EventArgs e)
{
var chk = ((TextBox)sender).NamingContainer.FindControl("CheckMark");
chk.Visible = true;
}
protected void GridSelecting(object sender, GridViewSelectEventArgs e)
{
this.GridView1.SelectedIndex = e.NewSelectedIndex;
}
Note: I'm sure that the original OP meanwhile has found the answer or a workaround by himself, maybe it'anyway helpful for someone else to see the differences between this simplified working sample and his own code
精彩评论