Programmers’ log has been moved !!
Proragmmers’ log has been moved to http://codelog.blogial.com. Me and my friend have started a social blogging network — blogial. So from now Programmers’ log will be Codelog under blogial. As i have told you, its a social blogging network and if any one wants to have a blog, they can very well mail us at blogials@gmail.com and get their blog ready.
ListView control in C#
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
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.
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
- ListView — LargeIcons mode
- ListView — Details mode
- ListView — SmallIcons mode
- ListView — Tile mode
- ListView — Tile mode
- ListView — HotTracking enabled
- ListView — Grids enabled
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.
Resource Managers and VS (Visual Studio) — a better understanding
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.
Customizing Combo Boxes
.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,
- Have a custom class that defines the Combo Box items
- Create an item of this class and add it to the Combo Box
- Handle the paint event of the Combo Box so that you can print (draw) as you wish over the Combo Box
- Handle the SelectedIndexChanged event of the Combo Box to decide on the behavior of the Combo Box
- 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)
Masked TextBox in C#
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
- Draw a TextBox in to your form
- Handle the KeyPress event of the TextBox
- Have a Regex object initialised to the mask pattern
- 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)
Regular Expressions in C#
RegularExpressions (AKA: Regex) are special strings that define a search pattern. Writing regex in C# is much similar to those you write in python. Some of the important keywords to be learnt before going in for Regex in C# are,
^ – denotes the start of the string
$ – denotes the end of the string
? – zero or one of the preceding element
* – zero or more of the preceding element
+ – one or more of the preceding element
\d – digits
\s – white space
\w – word (characters – including numbers)
\D – non digits
\S – non white space
\W – non word
{m,n} – between m and n times of the preceding element
{n} – n times of the preceding element
For example,
(foo){3} – will be a regex pattern and it will be matching the string “this is a foofoofoo” and it will not match “this is a foo foo foo”.
([+]{1})([\d]{2})-([\d]{2})-([\d]{8}) – will be matching +01-11-12345678
[\s](ROAD) – will be matching only ROAD in “BROAD ROAD” and not BROAD because it expects <whitespace> before “ROAD”
[a-zA-Z]* – will be matching any characters in the set a to z or A to Z, zero or more times
Using Regex in C#
- To use Regex in C#, you need a Regex object. So create one from the namespace, System.Text.RegularExpressions
- The constructor will take the pattern as string and the option that it needs to put in while doing the pattern matching process.
- After creating a Regex object we can search for the pattern in any input strings using the Regex.IsMatch() function. This function takes the input string and returns a boolean value based on the findings.
If you want to get the number of matches, you can use, Regex.Matches() which will return a MatchCollection object. Then to get the number of matches you can use MatchCollection.Count property.
For example,
using System.Text.RegularExpressions;
Regex mySearchPattern = new Regex("([+]{1})([\d]{2})-([\d]{2})-([\d]{8})");
string myInputString = "+01-11-12345678 \n +01-11-87654321";
if(mySearchPattern.IsMatch(myInputString))
{
MatchCollection aCollection = mySearchPattern.Matches(myInputString);
MessageBox.Show(aCollection.Count.ToString());
}
The above snippet will give an output as 2
Resource files in C#
Resource files are files that can hold resources like images, strings, icons, audio files, etc. These are xml files with the extension .resx. They are mainly helpful when the application uses images and NLS (Native Language Strings). To add and use a resource file in your application follow the steps.
- Right click on the Project from the Solution folder and select Add > New Item > Resource File.
- Enter an appropriate name for the file and click on Add.
- Your resource file is now created.
To add some strings to the resource files,
- Double click on the resource file to get the String table
- Enter the ID for a string and its corresponding value on the other field
- Save the resource file
You can also add images to the resource file by pressing Ctrl + 2, icons by pressing Ctrl + 3 and so on
To use it in the application
- Create an object of the ResourceManager class under the namespace System.Resources.ResourceManager
- To its constructor pass the arguments as, <namespace>.<classname> of the resource file as the first argument (If you are unaware of the resource file’s class name, then open the resource file’s designer.cs. Mostly it will be an internal class) and <assembly> of the namespace as the second argument. If it is in the same assembly then, typeof(<classname>.Assembly)
- Now you have created an object of the resource file
- To get the value of a string ID, you can use <resource object>.GetString( <stringID> )
For example,
using System.Resources;
ResourceManager stringTable = new ResourceManager(”Workspace.Resource”, typeof(Resource).Assembly);
MessageBox.Show(stringTable.GetString(”FOO”));
The above snippet will get the value of the string FOO from the stringTable (Resource file)



