Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

c# - Changing Textbox text without firing TextChanged event

My application in C# has a Textbox with a txt_TextChanged event.

private void txt_TextChanged(object sender, EventArgs e)
{
  //Do somthin
}

But there's one specific part that I want to change txt.Text without firing the txt_TextChanged event.

txt.Text ="somthing" //Don't fire txt_TextChanged

How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no direct way to prevent the raising of events for the text property, however your event handler can use a flag to determine weather or not to perform a task. This i likely to be more efficient than attaching and detaching the event handler. This can be done by a variable within the page or even a specialized class wrapper

With a variable:

skipTextChange = true;
txt.Text = "Something";

protected void TextChangedHandler(object sender, EventArgs e) {
  if(skipTextChange){ return; }
  /// do some stuffl
}

With specialized event handler wrapper

   var eventProxy = new ConditionalEventHandler<EventArgs>(TextBox1_TextChanged);
    TextBox1.TextChanged = eventProxy.EventAction;

    eventProxy.RaiseEvents = false;
    TextBox1.Text = "test";


    public void TextBox1_TextChanged(object sender, EventArgs e) {
       // some cool stuff;
    }

    internal class ConditionalEventHadler<TEventArgs> where TEventArgs : EventArgs
{
   private Action<object,TEventArgs> handler;

    public bool RaiseEvents {get; set;}

    public ConditionalEventHadler(Action<object, TEventArgs> handler)
    {
        this.handler = handler; 
    }

    public void EventHanlder(object sender, TEventArgs e) {
      if(!RaiseEvents) { return;}
      this.handler(sender, e);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...