Domanda

I want to know about what happens if :

 private void tbName_TextChanged(object sender, EventArgs e)
 {
   var s=sender as TextBox;
   s.Text="Hello";

   s.Dispose();

 }

And is it right way to manage some Events? I dont want to write some like this:

if(textbox1.Text.Equals(textbox2.text))
  {...}

And so on.

EDIT: i like to write some function:

 public bool isTextEquals(Object sender,String text)
  {
    var s =sender as TextBox;
    if(s.Text.Equals(text))
         return true;
    return false;   
  }

Will this function works well? Can be some memory leaks in this code?

È stato utile?

Soluzione

The event handler that you have for TextChanged event seems strange to say the least. Under normal circumstance you aren't likely to do something like this. There are more convenient ways of accessing your textbox that raised the event.

For example:

private void tbName_TextChanged(object sender, EventArgs e)
{   
   tbName.Text="Hello";
}

Disposing the textbox is a big huge No No in this case as you will actually destroy the textbox that is being used so the effect of that statement will not be what you would expect. In fact you rarely have to concern yourself with disposing of objects and controls in .Net as the framework does a pretty good job at managing that for you behind the scenes.

Now as far as comparisons are concerned this is perfectly legal and a lot more readable :

var comparisonResult = sometextbox.Text == "Some text i want to compare";

The equality operator == will do the work for you and will be a lot easier to read and maintain later on. No need for messy the If Statement.

On a side note I would recommend for you to get some introductory .Net and C# books to get a better understanding of the framework and it's features.

Hope this helps.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top