Monday, June 06, 2005

Windows Forms Controls Notes

  • Properly Updating Data Grid Bound Values: If you ever run into a situation where you have a Data Grid bound to a Data Source and another control, such as a TextBox or ComboBox, and it's bound to the same Data Source and modifying the bound value of that control does not immediately cause the modified value to appear in the Data Grid, I have the reason why: validation. Normally, when a situation like this occurs, simply tabbing through the controls causes the modified value to appear in the bound Data Grid. That's because the validation events are raised which in return call the control's Refresh() method. Refresh() causes the bound control(s) to invalidate their area and redraw. This includes, in this example, any data within a Data Grid. In order for you to properly update a bound Data Grid's data whenever a bound control modifies it's values, you need to 1) first place the Focus() on the container that holds the Data Grid (a Form, GroupBox, etc.), 2) secondly, place the Focus() on the Data Grid itself and then 3) thirdly, call the Data Grid's Refresh() method.
  • Properly Handling KeyPress, KeyDown and KeyUp Events: always set the KeyPressEventArgs's Handled property to true whenever you want to AVOID the key pressed being sent to the application. For example, if you're checking a TextBox control to determine whether or not a user has entered a non-digit character and don't want that character to end up in the TextBox accordingly then set the Handled property to true:
      private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
      {
       if (! Char.IsDigit(e.KeyChar)) 
       {
        MessageBox.Show("No non-digit characters allowed.");
        this.textBox1.Undo();
        e.Handled = true; // Key press will not be sent!
       }
       else
        e.Handled = false;
      }
  • Tab Order: To enable this feature, 1) first select the form on which you want to set a tab order structure, 2) click on View and then Tab Order from the VS.NET menu and then 3) click on each control in the order in which you want tabbing flow to follow.

No comments: