Programmers’ Log

foreach(Snippet aSnippet in ProgrammersLog){ aSnippet.GetSolution(); }

Archive for the ‘UI’ Category

Using ListView control in C#

with 8 comments

Recently I had to design a dialog that will have some control in the form of ListBox with each item again having a CheckBox, two to three labels and one image. I was trying out some control and I came to know about the ListView control. In my last post, I was talking about the features that are provided by it. Now lets try to find out ways to use those properties.

Note – All the below mentioned features can be enabled using the Property window (F4), but I personally prefer the code way of doing it as I don’t like the auto generation part of VS (Visual Studio)

Adding a ListViewControl to the application
ListView control, like the other control can be added using the following snippet

private System.Windows.Forms.ListView myListView; //Decleration of a ListView control
this.Controls.Add(myListView); //Adding the control to the application

Changing the Display modes
In my last post I had posted some screenshots showing various display modes for the ListView control. We can set those using the View property of the ListView control.

myListView.View = System.Windows.Forms.View.SmallIcon; //Can be any mode (refer to the previous article to know about the modes)

Adding items in to the list (when the ListView is not under the Details view)
The following snippet will be able to add items to the ListView control if it is not under the Details view. Addition of items differ by Views because Details view will have columns (which will be discussed next). If the ListView control’s View is a normal, say SmallIcon view then we do it the following way.

//The following method has around 6 overloads. Now we will just consider the 2 one -- the string parameter
myListView.Items.Add("foo");
myListView.Items.Add("bar");
myListView.Items.Add("baz");

Adding Columns to the ListView
As I have already told, we need to create columns before adding Items in to the ListView control under the Details view. So here is the way to create columns in the ListView control.

//Adding columns to the ListView control
myListView.Columns.Add("S.No");
myListView.Columns.Add("FileName");
myListView.Columns.Add("FilePath");

Adding items in to the list (when the ListView is under the Details view)
After the addition of columns, we can add any number of items to the ListView control. An item in here will be categorised in to two — Parent and Children. Parent will be the item’s main field(ListViewItem), while the child will be the ListViewSubItem.

ListViewItem aFooItem = new ListViewItem("1"); //Parent item
ListViewItem.ListViewSubItem aSubFooItem1 = new ListViewItem.ListViewSubItem(aFooItem, "Foo"); //Creating subitems for the parent item
ListViewItem.ListViewSubItem aSubFooItem2 = new ListViewItem.ListViewSubItem(aFooItem, "FooBarBaz/Foo");
aFooItem.SubItems.Add(aSubFooItem1); //Associating these subitems to the parent item
aFooItem.SubItems.Add(aSubFooItem2);
myListView.Items.Add(aFooItem); //Adding the parent item to the listview control

Adding separate styles to the subitems
In the Details mode, if we wanna add subitems that appear different from the parent item (Styling informations), then make the property UseItemStyleForSubItems to true. This property will be under the ListViewItem object. Doing so will allow us to specify seperate style informations for the subitems.

Removing items
Removing items is simple.

using Remove() method
//Remove method takes an object of ListViewItem. So create an object of ListViewItem for the item that needs to be deleted
//and call the method Remove() passing the object that you have created
ListViewItem aFooItem = new ListViewItem("foo");
myListView.Items.Add(aFooItem);
myListView.Items.Remove(foo);

using RemoveAt()
myListView.Items.RemoveAt(0);

Associating images with the list items
This is a nice feature, where we can add images to the ListViewItems (but I am not sure about the number of images that an item can have). For this, we need to have a ImageList with a set of images. Refer how to add images to image list before proceeding. This is done using one of the overloads of the ListView.Items.Add() method that involves ImageIndex. ImageIndex is the index of the image in the ImageList that is associated with the ListView control. ImageList is a list of images. Its like an array of images with an index associated with each images in the image list (called the Imageindex).

myListView.SmallImageList = myImageList; //ImageList where you have the set of images
myListView.Items.Add("foo", 0); //Where the 0 represents the ImageIndex of the image in the imagelist
myListView.Items.Add("bar", 1);
myLIstView.Items.Add("baz", 2);

Adding checkboxes as ListItems

This will enable us to put a CheckBox in each and every row. The programmer can handle the check box’s events through ItemCheck(before state change, this is called) and ItemChecked(after state change, this is called)

myListView.CheckBoxes = true; //To enable the CheckBox mode for the ListView control
myListView.ItemChecked += new ItemCheckedEventHandler(ItemChecked);

These are some of the commonly used features of ListView control.

Written by sudarsanyes

July 18, 2008 at 10:47 pm

Posted in C#, Controls, UI

Tagged with , , , , ,

ListView control in C#

with one comment

ListView control is like a ListBox control but with more functionalities. With such a control one can get a pane that looks excatly like the right pane in windows explorer. Certain stuffs that stand out in this control when you compare it with the ListBox control are,

Views
ListView control has many views like,

  • LargeIcon - The list items are listed as tiles (the usual windows tile view style). There will not be any horizontal scrollbar by default in this view
  • Details - The list items will have more columns that tells about addition information of any item
  • SmallIcon - Similar to LargeIcon, but will have small images to the left of eash item
  • List - The usual ListBox style
  • Tile - Combination of ListStyle and LargeIcon style views

ImageList
Using ListView control one can assiciate images with list items

Checkboxes
We can even add checkboxes to each and every items. This is not supported in Tile view though

HotTracking

Having items that behaves like hyperlinks

Columns
In the Details view one can have many columns and items can be added under each column (like the windows explorer Details view style). On can even sort things under the ListView control just by clicking the headers of the ListView control.

Grids

Under the Details view, we can display items in grids, giving it the classic datagrid view style

Tooltip text
Show tooltips for the list items just by making this property to true

This post is intended to be an introduction to the functionalities of a ListView control. My next post will be about the ways of using these funtionalities.

Written by sudarsanyes

July 16, 2008 at 6:20 pm

Posted in C#, Controls, UI

Tagged with , ,

Resource Managers and VS (Visual Studio) — a better understanding

without comments

Have you ever tried to find out what happens if you add a picture box and import an image in to it. Lets peep in to such a senario.

The usual one

Here we add a pictuebox and we use the properties window to assign it some image after importing it to the resource file.

When we run the application, we will be able to see the image in the picturebox.

The hidden one

When you add a picture control and an image to it, a lot of things are done in the background by the VS. It may appear to be easy but its really frustrating as such a process is not transparent. Each and every project will have a resource file by the name Resource.resx. When you double click it, you may get a string table or an image area, but actually its an xml file. Try opening the same file using right click and ViewSource — you will see an xml file. Now when you add any images or strings to such a table you are actually writing xml tags. But VS does it for you. Lets try to do the job of VS now.

  • Put a picture box in to your form
  • Open the resource file (xml form of the file)
  • Open the WindowsExplorer and navigate to the project folder
  • Create a folder called Resources under your project folder (this folder will be automatically created if you try to add some images to the resource file)
  • Put some bitmaps under this folder (say 1.bmp, 2.bmp and so on)
  • Coming back to the xml file, write the following


<data name="image1" type="System.Resources.ResXFileRef">
<value>..\..\Resources\1.bmp;System.Drawing.Bitmap</value>
</data>

Now go to your class and start accessing the image that you have added manually using the following snippet

pictureBox1.Image = global::<your_name_space>.Resource.image1

Now try running the application. You should be seeing the image on the pictureBox.

Whats the meaning ??

In the xml file the data tag’s name attribute will be like a variable name (some kinna id) and the name given for your image in here will be image1 and the type attribute will tell the .NET csc that its a resource that is linked in to the project. The value tag is the one that can be replaced with the path of any images (full file name). So ..\..\ … refers to the path of the image and the statement after ; tells the csc that the referenced resource object is of type Bitmap and to use System.Drawing.Bitmap class to create an object for it (object’s name will be ?? image1). This is what is happenning in VS when you add an image to the resource file.

Written by sudarsanyes

July 15, 2008 at 10:22 pm

Posted in C#, UI

Tagged with , , ,

Customizing Combo Boxes

with one comment

.Net comes with the Combo Box control, but that Combo Box does not have any features of adding disabled items in to it. If you want to disable some items from the Combo Box you need to do the following,

  1. Have a custom class that defines the Combo Box items
  2. Create an item of this class and add it to the Combo Box
  3. Handle the paint event of the Combo Box so that you can print (draw) as you wish over the Combo Box
  4. Handle the SelectedIndexChanged event of the Combo Box to decide on the behavior of the Combo Box
  5. Override the ToString() of the custom class so that you can decide what to return when the Combo Box control.Add(item) is called

Explanation:

  • Handling the paint event of any control under the OwnerDrawn mode will allow the user to choose what to paint when it is rendered on the screen. Using such a facility we can draw the unavailable items in Gray color there by giving the user a feel that the item is disabled.
  • Handling the behavior is tricky. This can be done by holding a class level variable which can store the Index value of the previously clicked available function. Such a variable will be altered whenever the user clicks on an available function and remains the same in the other case.

For example,

using System.Windows.Forms;

private ComboBox myFunctions = new ComboBox();

<In yourFormComboBox class>

myFunctions.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
myFunctions.DrawItem += new DrawItemEventHandler(Functions_DrawItem);
myFunctions.SelectedIndexChanged += new EventHandler(Functions_SelectedIndexChanged);

private int myPreviouslySelectedIndex;  //initialise it to 0 in the constructor of this class

//adding the items to the ComboBox
ComboBoxFunction aComoboBoxFunction = new ComboBoxFunction("SUMMATION");
aComboBoxFunction.IsAvailabel = true;
aComoboBoxFunction = new ComboBoxFunction("DIFFERENCE");
aComboBoxFunction.IsAvailabel = true;
aComoboBoxFunction = new ComboBoxFunction("MULTIPLICATION");
aComboBoxFunction.IsAvailabel = false;

private void Function_DrawItem(object sender, DrawItemEventArgs args)
{
  //handling the appearance of the ComboBox
  int aCurrentIndex = args.Index; //gets the index value of the current ComboBox item that is drawn in
the screen
  ComboBoxFunction aFunction = myFunctions[index] as ComboBoxFunction; //type casting to the custom object
  if(aFunction.IsAvailabel)
  {
    args.Graphics.DrawString(aFunction.ToString(), new Font("Arial", 10, FontStyle.Regular,
GraphicsUnit.Pixel), Brushes.Black, new Point(args.Bounds.X, args.Bounds.Y));
  }
  else
  {
    args.Graphics.DrawString(aFunction.ToString(), new Font("Arial", 10, FontStyle.Regular,
GraphicsUnit.Pixel), Brushes.Gray, new Point(args.Bounds.X, args.Bounds.Y));
  }
}

private void Function_SelectedIndexChanged(object sender, EventArgs args)
{
  //handling the behavior of the ComboBox
  ComboBoxFunction aFunction = myFunctions.SelectedItem as ComboBoxFunction;
  if(aFunction != null)
  {
    if(aFunction.IsAvailable)
    {
      myPreviouslySelectedIndex = myFunctions.SelectedIndex;
    }
    else
    {
      //myPreviouslySelectedIndex remains the same
      myFunctions.SelectedIndex = myPreviouslySelectedIndex;
    }
  }
}

class ComboBoxFunction
{
  private string myID;
  private string myValue;
  private bool myIsAvailable;
  private static System.Resources.ResourceManager myResource = new
System.Resources.ResourceManager("ComboBoxExample.FormComboBox", typeof(FormComboBox).Assembly);
  public string ID
  {
    get { return ID ; }
  }

  public string Value
  {
    get { return myValue; }
  }

  public bool IsAvailabel
  {
    get { return value; }
    set { myIsAvailable = value; }
  }

  public ComboBoxFunction(string theID)
  {
    myID = theID;
    if(myID != null)
    {
      myValue = myResource.GetString(ID);
    }
    myIsAvailabel = false;
  }

  public override string ToString()
  {
    return myValue;
  }
}

The above snippet will gives us a NLS (Native Language Supported) Combo Box with items SUMMATION (value of summation from the string table) enabled (black in color), DIFFERENCE enabled (again black in color) and MULTIPLICATION disabled (gray in color)

Written by sudarsanyes

July 4, 2008 at 1:09 pm

Posted in C#, Controls, UI

Tagged with ,

Masked TextBox in C#

without comments

Masked TextBoxes are those that won’t allow (or that will allow) certain strings, numbers or characters or patterns. Such kind of control is already present in the C#.Net with the name MaskedTextBox. This tutorial will suggest another way of doing such a TextBox in simple steps.

We will be using Regex in this tutorial. Its suggested that you have a look at the keywords used in writing Regex patterns [ RegularExpressions ].
RegexPal is an online regex tester. Its really handy at times.

Follow these steps to get a custom made masked textbox. We will be using Regex for specifying the mask

  1. Draw a TextBox in to your form
  2. Handle the KeyPress event of the TextBox
  3. Have a Regex object initialised to the mask pattern
  4. In the KeyPress handler use the Handled property of the KeyPressEvent to decide on whether to accept the key that has been pressed or not

Make sure that your Regex has ^ and $ at the beginning and end of the pattern

For example,

using System.Windows.Forms;

TextBox myCustomMaskedTextBox = new TextBox();
this.Controls.Add(myCustomMaskedTextBox);

Regex myPattern = new Regex(@"^[0-9]*$");
myCustomMaskedTextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CustomTextBoxKeyPressed);

private void CustomTextBoxKeyPressed(object sender, KeyPressEventArgs args)
{
//to allow the backspace key for deletion of the characters
if(args.KeyChar = '\b')
{
string t= myCustomMaskedTextBox.Text + args.KeyChar.ToString();
if(myRegex.IsMatch(t))
{
//pass
}
else
{
args.Handled = true;
}
}
}

The above snippet will allow the user to enter only numbers in to the textbox. Nothing else (except backspace)

Written by sudarsanyes

July 3, 2008 at 1:00 am

Posted in C#, Controls, Regex, UI

Tagged with , ,