Friday, June 8, 2007

Useful C# Code Snippets

Mapping a month name to its chronological order value

The following C# code can be used to map a month name to its equivalent numeric chronological order value. You can use this code in a method and pass the month in as a string to convert for example "JUN" to 06. You can modify the array to map the full month name in place of it's three letter abbreviation.

public string MonthToNumberMapper(string month)
{
string Month = month.ToUpper();
string ConvertedMonth = null;
string[,] MonthsToConvert = new string[,]
{
{ "JAN", "01" }, { "FEB", "02" }, { "MAR", "03" }, { "APR", "04" },
{ "MAY", "05" }, { "JUN", "06" }, { "JUL", "07" }, { "AUG", "08" },
{ "SEP", "09" }, { "OCT", "10" }, { "NOV", "11" }, { "DEC", "12" }
};

// Determine the numeric month.
for (int i = 0; i < MonthsToConvert.Length / 2; i++)
{
if (Month == MonthsToConvert[i, 0])
{
ConvertedMonth = MonthsToConvert[i, 1];
break;
}
}

return ConvertedMonth;
}

Converting the text in a ComboBox Control to Uppercase
The following C# code can be placed in the TextChanged event handler of a ComboBox Control to change the case of the text entered to uppercase. This works for text entered into or selected within the ComboBox Control.

private void StateComboBox_TextChanged(object sender, EventArgs e)
{
String stateText = (string)StateComboBox.Text;
stateText = stateText.ToUpper();
StateComboBox.Text = stateText;
installStateComboBox.SelectionStart = installStateComboBox.Text.Length;
}

3 comments:

Israel Gastelum said...

Tengo otra solucion... espero les sirva....
private void cboConcepto_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
ComboBox cboX = sender as ComboBox;

if(Char.IsLetter(e.KeyChar) || Char.IsWhiteSpace(e.KeyChar))
{
e.Handled = true;
if(cboX.SelectionStart == cboX.Text.Length)
{
cboX.Text += Char.ToUpper(e.KeyChar);

cboX.SelectionStart = cboX.Text.Length;
}
else
{
int intIndice = cboX.SelectionStart;

cboX.Text = cboX.Text.Insert(intIndice,Char.ToString(Char.ToUpper(e.KeyChar)));

cboX.SelectionStart = ++intIndice;
}
}
}

Mark said...

The MonthToNumberMapper function could be condensed into one line using this method:.

Private Function MonthToNumberMapper(ByVal MonthName As String) As Integer
Return CDate("1900-" & MonthName & "-01").Month
End Function

Dave said...

private void cboApplicationName_KeyPress(object sender, KeyPressEventArgs e)
{
e.KeyChar = char.Parse(e.KeyChar.ToString().ToUpper());
}