Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

Archive for WinForms

December 15, 2010

Setting a Form as a Startup Form with Visual Studio

Filed under: C#,VB.NET,WinForms @ 4:03 pm

The startup form is the first form that is launched when your application is executed. By default, a Windows Forms project creates a default form when the project is created. This form is set as the startup form.

You can change the startup form to any form within your application following the steps below. In this example, the report form is set as the startup form for testing purposes.

To Set a Form as a Startup Form:

In C#:

Modify the Program.cs file as follows:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new ReportWin());
}

In VB:

1) Double-click on My Project under the project in Solution Explorer.

2) Click the Application tab.

3) Set the Startup form.

image_thumb10

Use this technique any time you want to change the start up form for the application.

Enjoy!

November 19, 2010

Associating Code with a Tag using Delegates II

Filed under: C#,Lambda Expressions,VB.NET,WinForms @ 11:32 am

This prior post demonstrated how to use delegates to associated code with a Tag in a WinForms control. This post shows how to accomplish the same thing using Lambda expressions to define the delegate.

To try out this example, create a WinForms application and add a TreeView control to the form. Then add the code below.

In C#:

public delegate void DisplayMessage(string value);

private void Form1_Load(object sender, EventArgs e)
{
    var rootTreeNode = treeView1.Nodes.Add("Phones");

    var appleTreeNode = rootTreeNode.Nodes.Add("IPhone is the best");
    appleTreeNode.Tag = new DisplayMessage(
                          x => MessageBox.Show("Apple: " + x));

    var microsoftTreeNode = rootTreeNode.Nodes.Add("Win 7 Phone is the best");
    microsoftTreeNode.Tag = new DisplayMessage(
                          x => MessageBox.Show("Microsoft: " + x));

    treeView1.ExpandAll();
}

private void treeView1_DoubleClick(object sender, EventArgs e)
{
    var messageDelegate = (DisplayMessage)treeView1.SelectedNode.Tag;
    messageDelegate.Invoke(treeView1.SelectedNode.Text);
}

In VB:

Public Delegate Sub DisplayMessage(ByVal value As String)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim rootTreeNode = TreeView1.Nodes.Add("Phones")

    Dim appleTreeNode = rootTreeNode.Nodes.Add("IPhone is the best")
    appleTreeNode.Tag = New DisplayMessage(
                         Sub(x) MessageBox.Show("Apple: " & x))

    Dim microsoftTreeNode = rootTreeNode.Nodes.Add("Win 7 Phone is the best")
    microsoftTreeNode.Tag = New DisplayMessage(
                        Sub(x) MessageBox.Show("Microsoft: " & x))

    TreeView1.ExpandAll()
End Sub

Private Sub TreeView1_DoubleClick(ByVal sender As Object, 
                ByVal e As EventArgs) Handles TreeView1.DoubleClick
    Dim messageDelegate = TryCast(TreeView1.SelectedNode.Tag,
                                                DisplayMessage)
    If messageDelegate IsNot Nothing Then
        messageDelegate.Invoke(TreeView1.SelectedNode.Text)
    End If
End Sub

The first line of code declares a delegate. If you have not worked with delegates before, see this prior blog post for more information.

The Load event populates the Treeview with two child nodes. A new instance of the delegate is stored in the Tag property of each node.

The delegate instance constructor defines the code to call when the user double-clicks on the node. This code is defined using a Lambda expression. If you have not worked with a Lambda expression before, see this prior blog post for more information.

The DoubleClick event then pulls the delegate from the Tag property and calls it using the Invoke method, passing the appropriate parameters.

Use this technique any time you want to define code to execute in the Tag property of a control.

Enjoy!

Associating Code with a Tag using Delegates

Filed under: C#,VB.NET,WinForms @ 11:17 am

Many of the Windows Forms controls have a Tag property that you can use to store data associated with the control. For example, TextBoxes have a Tag property so you could store additional information about each TextBox in the Tag. For TreeView controls, each node has its own Tag property, so you can associate data with each node. But what if you wanted to associated code with each Tag?

This post details how to use delegates to associated code with a Tag. It uses a TreeView as an example, but any control with a Tag property could use this technique.

If you want to use a Lambda expression instead of a method to define the delegate, see this later post.

To try out this example, create a WinForms application and add a TreeView control to the form. Then add the code below.

In C#:

public delegate void DisplayMessage(string value);

private void Form1_Load(object sender, EventArgs e)
{
    var rootTreeNode = treeView1.Nodes.Add("Phones");

    var appleTreeNode = rootTreeNode.Nodes.Add("IPhone is the best");
    appleTreeNode.Tag = new DisplayMessage(AppleMessage);

    var microsoftTreeNode = rootTreeNode.Nodes.Add("Win 7 Phone is the best");
    microsoftTreeNode.Tag = new DisplayMessage(MicrosoftMessage);

    treeView1.ExpandAll();
}

public void  AppleMessage(string value)
{
    MessageBox.Show("Apple: " + value);
}
public void MicrosoftMessage(string value)
{
    MessageBox.Show("Microsoft: " + value);
}

private void treeView1_DoubleClick(object sender, EventArgs e)
{
    var messageDelegate = (DisplayMessage)treeView1.SelectedNode.Tag;
    messageDelegate.Invoke(treeView1.SelectedNode.Text);
}

In VB:

Public Delegate Sub DisplayMessage(ByVal value As String)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim rootTreeNode = TreeView1.Nodes.Add("Phones")

    Dim appleTreeNode = rootTreeNode.Nodes.Add("IPhone is the best")
    appleTreeNode.Tag = New DisplayMessage(AddressOf AppleMessage)

    Dim microsoftTreeNode = rootTreeNode.Nodes.Add("Win 7 Phone is the best")
    microsoftTreeNode.Tag =
                     New DisplayMessage(AddressOf MicrosoftMessage)

    TreeView1.ExpandAll()
End Sub

Public Sub AppleMessage(ByVal value As String)
    MessageBox.Show("Apple: " & value)
End Sub

Public Sub MicrosoftMessage(ByVal value As String)
    MessageBox.Show("Microsoft: " & value)
End Sub

Private Sub TreeView1_DoubleClick(ByVal sender As Object,
                ByVal e As EventArgs) Handles TreeView1.DoubleClick
    Dim messageDelegate = TryCast(TreeView1.SelectedNode.Tag,
                                               DisplayMessage)
    If messageDelegate IsNot Nothing Then
        messageDelegate.Invoke(TreeView1.SelectedNode.Text)
    End If
End Sub

The first line of code declares a delegate. If you have not worked with delegates before, see this blog post for more information.

The Load event populates the Treeview with two child nodes. A new instance of the delegate is stored in the Tag property of each node. The delegate instance defines the method to call when the user double-clicks on the node.

The AppleMessage method and the MicrosoftMessage method define the two methods to execute. These methods must have a signature that matches the signature of the delegate. In this case, it is a routine that takes one string parameter and does not return a value. But the delegate could define any signature and the methods must then match the delegate’s signature.

In this example, the methods displayed a messageBox, but the method could do anything. It could perform any type of calculation or perform any processing.

The DoubleClick event then pulls the delegate from the Tag property and calls it using the Invoke method, passing the appropriate parameters.

Use this technique any time you want to define code to execute in the Tag property of a control.

Enjoy!

October 29, 2010

Using Enter Key as a Tab

Filed under: C#,VB.NET,WinForms @ 1:51 am

A common question on the forums is how to use the Enter key instead of the Tab key to move through the controls on a Windows form. One common approach is to use SendKeys to send a Tab. But here is another option.

NOTE: To use this technique, set the KeyPreview property of the form to True.

In C#:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    Control nextControl ;
    if (e.KeyCode == Keys.Enter)
    {
        nextControl = GetNextControl(ActiveControl, !e.Shift);
        if (nextControl == null)
            nextControl = GetNextControl(null, true);
        nextControl.Focus();
        e.SuppressKeyPress = true;
    }
}

In VB:

Private Sub Form1_KeyDown(ByVal sender As Object,
         ByVal e As System.Windows.Forms.KeyEventArgs) _
                                     Handles Me.KeyDown
    Dim nextControl As Control
    If e.KeyCode = Keys.Enter Then
        nextControl = GetNextControl(ActiveControl, Not e.Shift)
        If nextControl Is Nothing Then
            nextControl = GetNextControl(Nothing, True)
        End If
        nextControl.Focus()
        e.SuppressKeyPress = True
    End If
End Sub

This code first checks the key that was pressed down and if it was the Enter key, processes it.

It uses the GetNextControl method to find the next control in the tab order. It checks the Shift key and if the Shift key is also pressed, GetNextControl finds the prior key in the tab order.

If GetNextControl does not find another control (because it runs into the end of the tab order), it calls GetNextControl again passing in a null to start back at the other end of the tab order.

For example, if you have four TextBoxes: 1,2,3,4, pressing the Enter key will move you from 1 to 2 to 3 to 4 and then back to 1. Pressing Shift + Enter will move you from 4 to 3 to 2 to 1.

Use this technique any time your users want to use the Enter key instead of the Tab key to move through the controls on a Windows form.

Hope this helps.

September 22, 2010

WinForms Checklist

Filed under: C#,VB.NET,WinForms @ 1:34 am

There are endless numbers of details you have to contend with when building great software. So it is easy to forget about some of the small ones, especially when it comes to the UI. So I use a checklist like this one to help ensure I covered all of my bases.

Form

  • Related  controls are grouped together
  • Controls are in a logical sequence
  • Controls are aligned appropriately
  • Tab order is set
  • Standard font family and size are set
  • Title bar text is descriptive

Modal Dialog

  • Minimize button disabled
  • Maximize button disabled

Resizable Dialog

  • Minimum size defined
    • Prevents the form from being resized too small to be usable
  • Controls appropriately anchored/docked to size as the dialog resizes
    • No resize code should be required in most cases

Controls

  • All text is spelled correctly
  • Labels are consistent in tense and terminology
  • Tooltips defined on all appropriate controls
  • Disabled controls are grayed out and not accessible
  • Buttons are all a consistent size and location on the screen

Validation

  • All required fields are validated
    • All required fields are distinguished in some manner, such as bolding the label, adding an asterisk, or highlighting the control (pick one technique and use it consistently)
  • All numeric fields are validated

Use this checklist as you finish each one of your WinForm UI components so you don’t have to sweat the details.

Enjoy!

August 17, 2010

Setting WinForms Colors to a Named, RGB, or Hex Value

Filed under: C#,VB.NET,WinForms @ 11:45 pm

Sometimes you want to add a little color to your WinForms controls. WinForms comes with a large set of named colors that you can use.

NOTE: Be sure to import a reference to System.Drawing.

For example

In C#:

textBox1.BackColor = Color.Linen;

In VB:

textBox1.BackColor = Color.Linen

But what if you want to display a color that is not one of the named colors? Then you can use the Color.FromArgb method to define your color by specifying the red, green, and blue values.

In C#:

textBox1.BackColor = Color.FromArgb(250, 245, 235);

In VB:

textBox1.BackColor = Color.FromArgb(250, 245, 235)

Ah, but what if you have the color defined as a hexadecimal value? Well, you could use Bing/Google to find a converter to convert it to RGB. Or you can use the ColorTranslator.FromHtml method.

In C#:

textBox1.BackColor = ColorTranslator.FromHtml("#FAF9F9");

In VB:

textBox3.BackColor = ColorTranslator.FromHtml("#FAF9F9")

Use any of these techniques to add some color to your WinForms applications.

Enjoy!

November 9, 2009

Populating a TreeView Control from a List

Filed under: C#,VB.NET,WinForms @ 11:25 pm

This post details first how to build a list containing the data to display in a WinForms TreeView control. Then it demonstrates how to use recursion to populate the TreeView control from the list.

[For information on populating a TreeView control from XML, see this link.]

First, create a class that will store the data for the TreeView.

In C#:

public class TreeViewItem
{
    public int ID { get; set; }
    public int ParentID { get; set; }
    public string Text { get; set; }
}

In VB:

Public Class TreeViewItem
    Public Id As Integer
    Public ParentId As Integer
    Public Text As String
End Class

The C# code uses auto-implemented properties to short-cut the code. The VB code is just me being lazy tonight. It is using Public fields instead of Public Properties as it should. (In VS 2010, VB will have auto—implemented properties as well.)

The class defines an Id associated with the item and a ParentId defining the Id of the parent item (that is the item under which this item will appear in the TreeView). It also has a Text property that contains the text of the TreeView node.

In the WinForm containing the TreeView control, add the code to build the list as shown below.

In C#:

List<TreeViewItem> treeViewList = new List<TreeViewItem>();

treeViewList.Add(new TreeViewItem() { 
          ParentID = 0, ID = 1, Text = "Parent node" });
treeViewList.Add(new TreeViewItem() { 
          ParentID = 1, ID = 2, Text = "First child node" });
treeViewList.Add(new TreeViewItem() { 
         ParentID = 1, ID = 3, Text = "Second child node" });
treeViewList.Add(new TreeViewItem() { 
         ParentID = 3, ID = 4, Text = "Child of second child node" });
treeViewList.Add(new TreeViewItem() { 
         ParentID = 3, ID = 5, Text = "Child of second child node" });

PopulateTreeView(0, null);

In VB:

Private treeViewList As New List(Of TreeViewItem)

treeViewList.Add(New TreeViewItem() With { _
        .ParentId = 0, .Id = 1, .Text = "Parent node"})
treeViewList.Add(New TreeViewItem() With { _
        .ParentId = 1, .Id = 2, .Text = "First child node"})
treeViewList.Add(New TreeViewItem() With { _
        .ParentId = 1, .Id = 3, .Text = "Second child node"})
treeViewList.Add(New TreeViewItem() With { _
        .ParentId = 3, .Id = 4, .Text = "Child of second child node"})
treeViewList.Add(New TreeViewItem() With { _
        .ParentId = 3, .Id = 5, .Text = "Child of second child node"})

PopulateTreeView(0, Nothing)

This code defines a generic List that contains the set of TreeViewItem instances. The Add method of the list sets the data into the list. It then calls the PopulateTreeView method (shown below).

The PopulateTreeView method uses recursion to populate the TreeView from the list.

In C#:

private void PopulateTreeView(int parentId, TreeNode parentNode)
{
    var filteredItems = treeViewList.Where(item => 
                                item.ParentID == parentId);

    TreeNode childNode;
    foreach (var i in filteredItems.ToList())
    {
        if (parentNode == null)
            childNode = treeView1.Nodes.Add(i.Text);
        else
            childNode = parentNode.Nodes.Add(i.Text);

        PopulateTreeView(i.ID, childNode);
    }
}

In VB:

Private Sub PopulateTreeView(ByVal parentId As Integer, _
                             ByVal parentNode As TreeNode)
    Dim filteredItems = treeViewList.Where(Function(item) _
                                     item.ParentId = parentId)

    Dim childNode As TreeNode
    For Each i In filteredItems.ToList()
        If parentNode Is Nothing Then
            childNode = TreeView1.Nodes.Add(i.Text)
        Else
            childNode = parentNode.Nodes.Add(i.Text)
        End If
        PopulateTreeView(i.Id, childNode)
    Next
End Sub

The PopulateTreeView method has two parameters: parentId and parentNode. The parentId is the Id value associated with the parent node. The code will find all items in the list with the defined parent Id. The parentNode is the TreeView node under  which the items are added.

The filteredItems variable contains the results of a lambda expression finding all of the items in the list with the passed in parentId.

The code then loops through those items and adds the nodes to the parent node.

It then calls itself, making the method recursive. The method call passes in the node’s Id and the node itself. This will cause the method to load all of its child nodes.

When you run the code, the TreeView should appear as follows:

image

Enjoy!

November 1, 2009

RichTextBox Styles

Filed under: C#,VB.NET,WinForms @ 12:42 am

If you are building a WinForms application and want to style your text, you may want to use the RichTextBox control instead of the standard TextBox control. This post provides some of the common techniques required to style text in a RichTextBox control.

To try out the examples in this post, build a new WinForms application. If desired, change the name of the form to "RichTextBoxSampleWin". Add a RichTextBox and two buttons to the form.

Setting Fonts/Colors

To set the fonts and colors of a RichTextBox, always select the text to style first, then set its font and color.

To try out setting fonts and colors, add this code to the Load event for the form:

In C#:

richTextBox1.Text = "That that is, is. That that is not, is not. "
                               + "Is that it? It is.";

// Set the style of the text
richTextBox1.SelectionLength = richTextBox1.Text.Length;
richTextBox1.SelectionFont = new Font("Arial", 12, FontStyle.Bold);
richTextBox1.SelectionColor = Color.DarkSlateBlue;
richTextBox1.SelectionStart = richTextBox1.Text.Length;

In VB:

richTextBox1.Text = "That that is, is. That that is not, is not. " & _
                                               "Is that it? It is."

‘ Set the style of the text
richTextBox1.SelectionLength = richTextBox1.Text.Length
richTextBox1.SelectionFont = New Font("Arial", 12, FontStyle.Bold)
richTextBox1.SelectionColor = Color.DarkSlateBlue
richTextBox1.SelectionStart = richTextBox1.Text.Length

The first line of code sets text into the RichTextBox.

The most important step here is to select the text that you want to style. Use the SelectionStart property to set the location in the text string to start the selection. If you don’t specify a selection start, it is assumed to start at the first character of the text. Use the SelectionLength property to specify the length of the selection. In this case, the entire length of text is selected to be styled.

NOTE: Instead of setting the SelectionStart and SelectionLength properties, you can use the Select method to set both the selection start and selection length at one time.

The next two lines set the font and color for the selected text. The last line resets the SelectionStart to the end of the text. This allows the user to type in further text.

If you run the application at this point, it should look like this:

image

If the user types in more text, it will follow the given style.

Setting Multiple Fonts/Colors

There are two basic ways to set multiple fonts and colors within the text:

  1. Add the text by appending to the Text property and then use SelectionStart and SelectionLength to select the appended text. Then style the selected text. This is similar to the approach used above.
  2. Set the styles and then use the AppendText property.

To try out technique #1, add the following code to the button click event for one of the buttons on the form:

In C#:

// Add another set of text in a different style
string addedText = Environment.NewLine + Environment.NewLine
                     + "This famous quote was from what movie?";
int len = richTextBox1.Text.Length;
richTextBox1.Text += addedText;
richTextBox1.SelectionStart = len;
richTextBox1.SelectionLength = addedText.Length;
richTextBox1.SelectionFont = new Font("Verdana", 10,
                                      FontStyle.Regular);
richTextBox1.SelectionColor = Color.DarkSlateGray;


In VB:

Dim addedText As String = Environment.NewLine & Environment.NewLine & _
                        "This famous quote was from what movie?"
Dim len As Integer = richTextBox1.Text.Length
richTextBox1.Text &= addedText
richTextBox1.SelectionStart = len
richTextBox1.SelectionLength = addedText.Length
richTextBox1.SelectionFont = New Font("Verdana", 10, FontStyle.Regular)
richTextBox1.SelectionColor = Color.DarkSlateGray

This code first stores the length of the current text. This will be the selection start value. The additional text is then appended to the Text property of the RichTextBox. The SelectionStart and SelectionLength are then set as in the prior example. Finally, the font and color are set.

NOTE: You must set the SelectionStart and SelectionLength after you append the text.

To try out technique #2, replace the code in the button click event with this code instead:

In C#:

// Add another set of text in a different style
string addedText = Environment.NewLine + Environment.NewLine
                     + "This famous quote was from what movie?";
richTextBox1.SelectionFont = new Font("Verdana", 10,
                                     FontStyle.Regular);
richTextBox1.SelectionColor = Color.DarkSlateGray;
richTextBox1.AppendText(addedText);

In VB:

‘ Add another set of text in a different style
Dim addedText As String = Environment.NewLine & Environment.NewLine & _
                        "This famous quote was from what movie?"
richTextBox1.SelectionFont = New Font("Verdana", 10, FontStyle.Regular)
richTextBox1.SelectionColor = Color.DarkSlateGray
richTextBox1.AppendText(addedText)

Notice how much shorter this option is. This technique sets the SelectionFont and SelectionColor and then uses the AppendText method to add the styled text to the RichTextBox.

Regardless of which technique you choose, the result will appear as follows:

image

Highlighting Words

Another common requirement when working with a RichTextBox is to highlight multiple occurrences of a specific word.

To try out this technique, add this code to the other button click event:

In C#:

string wordToFind  = "is";
int startIndex  = 0;

while (startIndex > -1)
{
    startIndex = richTextBox1.Find(wordToFind, startIndex + 1,
                    richTextBox1.Text.Length,
                    RichTextBoxFinds.WholeWord);
    if (startIndex > -1 )
    {
        richTextBox1.Select(startIndex, wordToFind.Length);

        richTextBox1.SelectionFont = new Font("Verdana", 12,
                                FontStyle.Bold | FontStyle.Italic);
        richTextBox1.SelectionColor = Color.Red;
    }
}

In VB:

Dim wordToFind As String = "is"
Dim startIndex As Integer = 0

Do While startIndex > -1
    startIndex = richTextBox1.Find(wordToFind, startIndex + 1, _
                    richTextBox1.Text.Length, _
                    RichTextBoxFinds.WholeWord)
    If startIndex > -1 Then
        richTextBox1.Select(startIndex, wordToFind.Length)

        richTextBox1.SelectionFont = New Font("Verdana", 12, _
                                FontStyle.Bold Or FontStyle.Italic)
        richTextBox1.SelectionColor = Color.Red
    End If
Loop

The code first defines the word to find. If this code is contained in a method instead of an event, the word to find could be passed in as a parameter.

The code then loops through the text in the RichTextBox using the Find method of the RichTextBox to find the next occurrence. The Find method will return –1 when it does not find any matches.

If a match is found, the code uses the Select method to select the found text. It then sets the font and color. This example also demonstrates how to bold AND italicize the text by Or’ing the style flags.

The result appears as follows:

image

Enjoy!

October 20, 2009

Populating a DataGridView from Xml Data

Filed under: C#,Data Binding,LINQ,VB.NET,WinForms,XML @ 11:49 pm

If you are using XML in a WinForms application you may find the need to display the XML data in a DataGridView.

Let’s take this XML:

<states>
    <state name="California">
        <abbreviation>CA</abbreviation>
        <year>1850</year>
        <governor>Schwarzenegger</governor>
    </state>
    <state name="Wisconsin">
        <abbreviation>WI</abbreviation>
        <year>1848</year>
        <governor>Doyle</governor>
    </state>
</states>

Displaying XML in a DataGridView sounds easy, but if you just set the DataGridView DataSource to the XML data, you will get something like this:

image

Notice how it has lots of yuck in it: attribute details, node properties, and so on for every node in the XML. So how do you get something more like this:

image

The trick is to use anonymous types.

The code is provided here in VB and C# and then described in detail below.

NOTE: Be sure to set a reference to System.Core and System.Xml.Linq

In C#:

XElement statesXml = XElement.Parse("<states>" +
    "<state name=’California’>" +
        "<abbreviation>CA</abbreviation>" +
        "<year>1850</year>" +
        "<governor>Schwarzenegger</governor>" +
    "</state>" +
    "<state name=’Wisconsin’>" +
        "<abbreviation>WI</abbreviation>" +
        "<year>1848</year>" +
        "<governor>Doyle</governor>" +
    "</state>" +
   "</states>");

var query = from st in statesXml.Descendants("state")
            select new
            {
                Name = st.Attribute("name").Value,
                Abbrev = st.Element("abbreviation").Value,
                Year = st.Element("year").Value,
                Governor = st.Element("governor").Value
            };
DataGridView1.DataSource = query.ToList();

In VB:

Dim statesXml As XElement = _
    <states>
        <state name="California">
            <abbreviation>CA</abbreviation>
            <year>1850</year>
            <governor>Schwarzenegger</governor>
        </state>
        <state name="Wisconsin">
            <abbreviation>WI</abbreviation>
            <year>1848</year>
            <governor>Doyle</governor>
        </state>
    </states>

Dim query = From st In statesXml…<state> _
            Select New With { _
                  .Name = st.@name, _
                  .Abbrev = st.<abbreviation>.Value, _
                  .Year = st.<year>.Value, _
                  .Governor = st.<governor>.Value}
DataGridView1.DataSource = query.ToList

The first part of this code builds the XML. The C# code uses the XElement.Parse function to build the XML; VB uses XML literals. This part of the code is not necessary if you are reading the XML from another source, such as a file.

The second part of the code leverages Linq to XML to process the set of state XML elements. For each element, it uses the Select New syntax to create an anonymous type. The syntax defines an unnamed (anonymous) type with properties Name, Abbrev, Year, and Governor.

[To view an overview of anonymous types, start here.]

The last line converts the results of the query to a generic list and assigns it to the DataSource property of the DataGridView. Visual Studio uses the anonymous type property names as the text for the column titles and populates the rows with each state element.

Use this technique any time you have XML that you want to display in a DataGridView.

Enjoy!

October 13, 2009

WinForms User Controls 101

Filed under: C#,VB.NET,WinForms @ 11:43 am

The same several questions often come up in the forums regarding the basics of building a user control with VB.NET or C#. The goal of this post is to answer those questions.

There are three basic types of WinForms user controls that you can create:

  • Extended control
  • Composite control
  • Custom control

Each of these are discussed below.

Extended Control

Use an extended control whenever you want to extend the behavior of one particular control. Say for example that you want to build your own TextBox that only allows alphabetic characters. Or you want to build your own Button that has specific behaviors.

The best thing about extended controls is that you automatically get all of the intrinsic behavior of the original control. All you need to do is add any extended functionality that you want for the control.

To create this type of user control, follow these steps.

In C#:

  1. Right-click on the project and select Add | User Control.
  2. Name the user control and click Add.
  3. Do NOT put anything on the design surface of the user control.
  4. Open the code behind file (UserControl1.cs).
  5. Modify the code to inherit from the control you are extending.

public partial class UserControl1 : TextBox

This example extends a TextBox control. Replace TextBox above with whatever WinForm control you want to extend.

NOTE: After changing the Inherits statement, you may get an error on a line that begins with this.AutoScaleMode. If so, just delete that line. It is no longer needed now that you are inheriting from a control other than UserControl.

In VB:

  1. Right-click on the project and select Add | User Control.
  2. Name the user control and click Add.
  3. Do NOT put anything on the design surface of the user control.
  4. Select the project in the Solution Explorer and click the Show All Files button in the Solution Explorer toolbar.
  5. Click on the plus sign to the left of the user control in Solution Explorer to view the nodes below it.
  6. Double-click on the designer file to open it. (UserControl1.Designer.vb)
  7. Modify the code to inherit from the control you are extending.

Partial Class UserControl1
    Inherits TextBox

This example extends a TextBox control. Replace TextBox above with whatever WinForm control you want to extend.

NOTE: After changing the Inherits statement, you may get an error on a line that begins with Me.AutoScaleMode. If so, just delete that line. It is no longer needed now that you are inheriting from a control other than UserControl.

Then add any additional behavior or functionality that you want in the extended control.

The MSDN documentation provides an example of building an extended control using VB.NET here and C# here.

Composite Control

A composite controls is so named because it is composed of multiple controls. Use this type of user control any time you want to build a control that combines a set of other controls. For example, you want to build a search control that contains a Textbox for entry of the text to search, Button to click to perform the search, and ListBox for the results of the search.

The best thing about composite controls is that you can easily add any controls to the composite control using the design surface.

However, because it is a composite control that inherits from UserControl, no properties, methods, or events from any of the underlying controls are exposed. This means that when you use the user control, you cannot set the Text property of the TextBox or respond to Button click events without writing some code.

You basically have to write code to expose any property, method, or event that you need.

To create this type of user control, follow these steps:

  1. Right-click on the project and select Add | User Control.
  2. Name the user control and click Add.
  3. Put the controls you want onto the design surface.
  4. Expose any properties, methods, or events that you need.

An example of generating events from a user control is provided in this post.

The MSDN documentation provides an example of building a composite control using VB.NET here and C# here.

Custom Control

A custom control is a control you create from the ground up including all control drawing and any unique behavior.

To build a custom control, inherit from Control to get the basic behavior of a WinForms control. Then use the OnPaint event to render your custom user interface.

The MSDN documentation provides an example of building a simple custom control here.

Enjoy!

Next Page »

© 2014 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs