Wednesday, April 30, 2008

Extracting string literals from Enum

public enum Users { Anonymous, Trainee, Developer, TeamLeader, Manager, Administrator}

A simple way to extracting the string constants from enum:

Type userType = typeof(Users);

// get names of users as string
string[] user = Enum.GetNames(userType);

// enum to string
string anonymous = Users.Anonymous.ToString();

// string to enum
Users manager = (Users)Enum.Parse(typeof(Users), "Manager", true);

Tuesday, April 29, 2008

Tip: Open partial class for a form in code view

When creating a partial class for a Form in Visual Studio, the "View Designer" button (or option) is shown. Also, opening (e.g. double click) the partial class for the form not only opens a blank form in the IDE but may also destroy the original one. However, for the Form.Designer.cs partial class, this "View Designer" option is not shown.

Is it possible to tell the VS IDE not to show the "View Designer" button for these partial classes?
Yes, one way you could tell the IDE not to show the form in the designer is to use the DesignerCategory Attribute.

public partial class MainForm

Steps to reproduce:
1. Create a new windows application.
2. Add a new class named PartialMainForm.cs
3. Add the partial keyword in front of the "class Form1" declaration in the added class.
4. Save everything.
5. Double click the PartialMainForm.cs file in the Solution Explorer.
6. A blank form appear.

Tuesday, April 1, 2008

Scroll Listbox Programmatically

String literals can be added to a ListBox control by using the Items.Add method. However, the ListBox control doesn't scroll automatically. One way to achieve this is to use the TopIndex property. This property determines the first entry to be visible in the ListBox.

Make the first entry visibile at the top of the ListBox:
this.listbox1.TopIndex = 0;

Show the last string of the control visible at the bottom of the ListBox (the last entry visible):
this.listbox1.TopIndex = this.listbox1.Items.Count - 1;