12 December 2007

Regular Expression : How to use in C#

Regular expression is a very useful tool for string matching. Through regular expression we can apply a pattern on an input string and return a list of matches within the text. Here I'll show how to use this important tool in C#. Constructing pattern is a very important thing. But I’ll not concentrate on that, rather use a simple pattern to show the way of implementation in C#.

► System.Text.RegularExpressions namespace is required.

The above namespace contains a class Regex. The most common constructor is public Regex(string pattern)

Regex contains a function named Match. Two important versions are

1. public static Match Match(string pattern, string inputString)

2. public Match Match(string inputString)

we can use 1st version without creating any instance of Regex, as it is a static function. To use the 2nd version, we must first create an instance of Regex.

Match function returns the result of matching the pattern within the inputString through a Match object.

Through Success attribute of Match class, we can know whether pattern successfully matches or not.

If successful, then we can know the index of inputString where the match starts at from the attribute Index of Match. Another attribute Value gives the matched part.

Sample program:

using System;
using System.Text;
using System.Text.RegularExpressions;
namespace RegeularExpressionTest
{
class Program
{
static void
Main(string[] args)
{
string inputStr = "i am a software engineer, not a mechanical engineer";
string pattern = "engineer";
Regex r = new Regex(pattern);
Match m = r.Match(inputStr);
printResult(m);
}
static void printResult(Match m)
{
if (m.Success)
Console.WriteLine("Pattern matched:\tIndex:{0}\tValue:\'{1}\'", m.Index, m.Value);
else
Console.WriteLine("Pattern did not match.");
}
}
}

/*
output:
-------
Pattern matched: Index:16 Value:'engineer'
*/

After getting one match, we can further search for more matches through the function nextMatch.

Sample program:

string inputStr = "i am a software engineer, not a mechanical engineer";
string pattern = "engineer";
Regex r = new Regex(pattern);
Match m = r.Match(inputStr);
printResult(m);
m = m.NextMatch();
printResult(m);
m = m.NextMatch();
printResult(m);

/*
output:
-------
Pattern matched: Index:16 Value:'engineer'
Pattern matched: Index:43 Value:'engineer'
Pattern did not match.
*/

The function Matches can be used to get all successful matches.

Sample program:

string inputStr = "i am a software engineer, not a mechanical engineer";
string pattern = "engineer";
Regex r = new Regex(pattern);
MatchCollection mc = r.Matches(inputStr);
foreach (Match m in mc)
printResult(m);

/*
output:
-------
Pattern matched: Index:16 Value:'engineer'
Pattern matched: Index:43 Value:'engineer'
*/

Regex can be used for matching from the last i.e. right to left. Here RegexOption has to be used. RegexOption can also used for case-insensitive match.

Regex can also be used for string replacing.

Sample program:

string inputStr = "i am a software EngInEer, not a mechanical enGiNeeR";
string pattern = "engineer";
Regex r = new Regex(pattern, RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
MatchCollection mc = r.Matches(inputStr);
foreach (Match m in mc)
printResult(m);

string replacingStr = "ENGR";
string replacedStr = r.Replace(inputStr, replacingStr);
Console.WriteLine(replacedStr);
/*
output:
-------
Pattern matched: Index:43 Value:'enGiNeeR'
Pattern matched: Index:16 Value:'EngInEer'
i am a software ENGR, not a mechanical ENGR
*/

11 December 2007

C#: ComboBox Customization

ComboBox is one of the most common GUI elements. It is used to provide the user the facility of selecting an item from a list or enter a new text. Here I’ll show you some common and useful functionalities of ComboBox in C# using Microsoft Visual Studio .Net 2005.

Simplest ComboBox:

In the simplest case, we add some strings in the list like the following-

myComboBox.Items.Add("Bangladesh");
myComboBox.Items.Add("
India");
myComboBox.Items.Add("
Pakistan");
myComboBox.Items.Add("Srilanka");
myComboBox.Items.Add("
Maldives");
myComboBox.Items.Add("
Nepal");
myComboBox.Items.Add("
Bhutan");

Sorted List:

Generally users expect that the options will be shown in sorted order. For this purpose, we have to add one line of code-


myComboBox.Sorted = true;

DropDownStyle:

In ComboBox, the user can either enter a text or just select an item from the list. So the developer should set its style. There are 3 options available:

  1. ComboBoxStyle.DropDownList: User can just select one item from a list.
  2. ComboBoxStyle.DropDown: User can either type a text or select an item from list.
  3. ComboBoxStyle.Simple: User can only type a text in text box. Item list is not shown.

Example:

myComboBox.DropDownStyle = ComboBoxStyle.DropDown;

Suggesstion/Dictionary:

When a user enters a text, he/she becomes happy if some suggestions are shown just below the combo box at the time of typing. For this functionality, we need to write couple of lines-

myComboBox.AutoCompleteSource = AutoCompleteSource.ListItems;
myComboBox.AutoCompleteMode = AutoCompleteMode.Suggest;

A Trick:

There may be a case where user selects some readable text, but for the programmer corresponding value (not the selected text) is important. For example, in database project StudentID is more important for a programmer than StudentName. So, it would be nice if we could add (Name, Value) combination in combo box and at the time of Name selection we could easily get the corresponding value.

We can do it by adding an object containing Name and Value.

class ComboBoxItem
{
public string Name;
public int Value;
public ComboBoxItem(string Name, int Value)
{
this.Name = Name;
this.Value = Value;
}
}


myComboBox.Items.Add(new ComboBoxItem("Ashis Saha",1));
myComboBox.Items.Add(new ComboBoxItem("Subrata Roy", 2));
myComboBox.Items.Add(new ComboBoxItem("Aminul Islam", 3));
myComboBox.Items.Add(new ComboBoxItem("Shakibul Alam", 4));
myComboBox.Items.Add(new ComboBoxItem("Tanvir Ahmed", 5));

But if you now see the list of ComboBox, you will notice that all items are same and they are the class names of those objects. In fact, the items are nothing but the output of the ToString() function of those objects. So if we simply override the ToString() function to behave as our expectation, we are done.

class ComboBoxItem
{
public string Name;
public int Value;
public ComboBoxItem(string Name, int Value)
{
this.Name = Name;
this.Value = Value;
}

// override ToString() function
public override string ToString()

{
return this.Name;
}

}

You can get the selected value in following way-

int selectedValue = ((ComboBoxItem)myComboBox.SelectedItem).Value;

 

© 2007 t!ps n tr!cks: 2007



Template unik dari rohman


---[[ Skip to top ]]---