WinForms tricks & tips

  • đź“…
  • đź“ť 308
  • đź•™ 2
  • 📦 .NET

TreeView right-mouse button select the node

I’m not sure why it doesn’t do this as standard but a simple event handler should do the trick:

private void treeView_MouseDown(object sender, MouseEventArgs e) {
    if (e.Button == MouseButtons.Right) {
    TreeNode node = treeView.GetNodeAt(e.X, e.Y);
    if (node != null)
        treeView.SelectedNode = node;
    }
}

Adding text to a text box

People have asked (in the IRC #CSharp) why adding text to a TextBox is so slow and flickery. Normally they are trying:

textBox1.Text += myNewText;

The problem with this is that it copies all the Text from the text box then adds myNewText to it and copies the whole result back. This is because strings in .NET are immutable, i.e. can’t be changed, and so adding one string to another always results in this overhead (and hence the existence of the StringBuilder class).

The solution is to abandon the slow, inefficient string concatenation and use the method AppendText thusly:

textBox1.AppendText(myNewText);

Which is fast and efficient whilst also being available to TextBox, RichTextBox and MaskedTextBox (by virtue of being a method of BaseTextBox).

They usually also ask how to make the text box scroll to the end. Just use the following line:

textBox1.ScrollToCaret();

Don’t forget keyboard input

Check those tab orders and accelerator keys!

Creating dynamic controls

If you’re ever unsure how to work with a dynamic control just create it in Visual Studio’s Designer and then head into the .designer.cs file and examine the code it generates.

Windows Forms FAQ

There are many other hints, tips and solutions in the Windows Forms FAQ.

[)amien

0 responses to WinForms tricks & tips

  1. Avatar for

    Information is only used to show your comment. See my Privacy Policy.