Tuesday, August 20, 2013

C# Capturing Keys - KeyPress Event, KeyDown Event or KeyUp Event

Differences of the three:
  1. Keydown: happens when the key is pressed.
  2. KeyPressed: happens when a key is pressed and then released.
  3. KeyUp: happens when the key is released.

Sample Code below :-

1.Create a Textbox control.

2.Adding event to your control in form1.designer.cs
 
this.textbox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CaptureKeyPress);
this.textbox1.KeyDown += new System.Windows.Forms.KeyEventHandler(CaptureKeyDown);
this.textbox1.KeyUp += new System.Windows.Forms.KeyEventHandler(CaptureKeyUp);
3.Creating event handler
 
private void CaptureKeyPress(object sender, KeyPressEventArgs e)
{
    //key press capture key char
    //you can compare with keycode also
    if (e.KeyChar == (char)Keys.Enter)
    {
        MessageBox.Show("Enter Key Press");
    }
    //or can compare with ascii code
    if (e.KeyChar == 13) //13 in ascii code for enter
    {
        MessageBox.Show("Enter Key Press");
    }
}

private void CaptureKeyDown(object sender, KeyEventArgs e)
{
    //key down capture key code
    if (e.KeyCode == Keys.Enter) 
    {
        MessageBox.Show("Enter Key Down");
    }
}

private void CaptureKeyUp(object sender, KeyEventArgs e)
{
    //key up capture key code
    if (e.KeyCode == Keys.Enter) 
    {
        MessageBox.Show("Enter Key Up");
    }
}
get list of key char from ascii table.. link below..
get list of key code from keys enum.. link below..

Additional Reading at :
  1. ASCII Table
  2. List Keys Enumeration
  3. MSDN KeyPress
  4. MSDN KeyDown
  5. MSDN KeyUp

Thursday, May 2, 2013

C# ComboBox using DataTable

Load Combobox Using DataTable.
Make an OleDbConnection.
Create DataTable from OleDbDataReader.

Sample code:
 
//include this
using System.Data.OleDb;

//declare 
OleDbConnection OCON = null;
OleDbDataReader ODR = null;
//create connection
OCON = new OleDbConnection(@"Provider=SQLOLEDB;Data Source=192.168.0.1;Initial Catalog=TESTDATABASE;User ID=TESTUSER;Password=TESTPASS;");

try{
    //open connection
    OCON.Open();            
    
    //create command    
    OleDbCommand OCMD = null;        
    OCMD.CommandText = "SELECT ID, DESCRIPTION FROM TABLE";
    //execute command
    ODR = OCMD.ExecuteReader();
    
    //load datareader to datatable       
    DataTable DT = new DataTable();
    DT.Load(ODR);

    //attach datatable to combobox
    comboBox1.DisplayMember = "DESCRIPTION";
    comboBox1.ValueMember = "ID";
    comboBox1.DataSource = DT;

    //close connection
    OCON.Close();
}catch(OleDbException ex){
    MessageBox.Show(ex.ToString());
}
Additional Reading at :
  1. MSDN OleDb
  2. MSDN ComboBox

Wednesday, May 1, 2013

C# string ToTitleCase. Capitalize the first letters of all words.

Convert string to title case. Capitalize the first letters of all words.


Sample code:
 
//include this
using System.Globalization;

//how to convert from uppercase string to titlecase
string title = "THE TITLE STRING";

TextInfo ti = CultureInfo.CurrentCulture.TextInfo;

title = ti.ToTitleCase(title.ToLower());

//result : "The Title String"
Additional Reading at :
  1. MSDN ToTitleCase

C# DateTimePicker CustomFormat Month and Year

Using DateTimePicker to select month and year only.
//to configure datetimepicker for month and year.

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MMM-yyyy";
dateTimePicker1.ShowUpDown = true;

//to get value of the datetimepicker.
dateTimePicker1.Value.ToString("yyyy-MM");


Additional Reading at :
  1. MSDN DateTimePicker
  2. MSDN CustomFormat
  3. MSDN ShowUpDown

Friday, April 26, 2013

C# Get Application Version via runtime

Setting Custom version number at project properties under application assembly information

Get application version via runtime code:

System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

C# Read Registry Method

To get value from registry. Sample code:
 
//include this
//for registry read write
using Microsoft.Win32; 

public string ReadRegistryValue(string KeyName)
{
            
    // Opening the registry key
    RegistryKey key = Registry.LocalMachine;
    // Open a subKey as read-only
    RegistryKey subkey = key.OpenSubKey(@"SOFTWARE\SKYPE\PHONE");
            
    // If the RegistrySubKey doesn't exist -> (null)
    if (subkey == null)
    {
        return null;
    }
    else
    {
        try
        {
            //return value
            return (string)subkey.GetValue(KeyName);
        }
        catch (Exception e)
        {
            //display error
            MessageBox.Show("Reading registry Exception " + e.Message.ToString());
            return null;
        }
    }
}

//method usage
 MessageBox.Show(ReadRegistryValue("SkypePath"));
Additional Reading at :
  1. MSDN RegistryKey

Wednesday, January 30, 2013

C# Create Delete Move Copy Rename Folder

Folder Manipulation (Create Delete Move Copy Rename Folder) in C# Sample Code:
 

//include this
using System.IO;

public void CreateFolder(string FolderPath)
{
    // Specify the directories you want to manipulate.
    DirectoryInfo di = new DirectoryInfo(FolderPath);
    try
    {
        //check folder already exists.
        if (di.Exists)
        {
            MessageBox.Show("Folder already exists.");

        }
        else 
        {
            //create folder
            di.Create();
        }  
    }
    catch (Exception e)
    {
        MessageBox.Show(e.ToString());
    }
}

public void DeleteFolder(string FolderPath)
{
    // Specify the directories you want to manipulate.
    DirectoryInfo di = new DirectoryInfo(FolderPath);
    try
    {
        //check folder exists.
        if (di.Exists)
        {
            //delete all including sub folder
            di.Delete(true);
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.ToString());
    }
}

public void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
    if (source.FullName.ToLower() == target.FullName.ToLower())
    {
        return;
    }

    // check target folder exists 
    if (Directory.Exists(target.FullName) == false)
    {
        //create target target folder
        Directory.CreateDirectory(target.FullName);
    }

    //copy each file to target folder
    foreach (FileInfo fi in source.GetFiles())
    {
        fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
    }

    //copy each sub folder to target folder
    foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
    {
        DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
        //copy all file from subfolder to target subfolder
        CopyAll(diSourceSubDir, nextTargetSubDir);
    }
}

public void MoveAll(DirectoryInfo source, DirectoryInfo target)
{
    try
    {
        //check source folder exist
        if(source.Exists)
            //check destination not exist
            if(!target.Exists)
                source.MoveTo(target.ToString());
    }
    catch (IOException e)
    {
        MessageBox.Show(e.Message);
    }
}

public void RenameTo(DirectoryInfo di, string NewName)
{
    if (di == null)
    {
        MessageBox.Show("Directory info to rename cannot be null");
    }

    if (string.IsNullOrWhiteSpace(NewName))
    {
        MessageBox.Show("New name cannot be null or blank");
    }

    di.MoveTo(Path.Combine(di.Parent.FullName, NewName));
}

//method usage
CreateFolder(@"C:\NewFolder");
DeleteFolder(@"C:\FolderToDelete");

DirectoryInfo Source = new DirectoryInfo(@"C:\SourceFolder");
DirectoryInfo Target = new DirectoryInfo(@"C:\TargetFolder");
CopyAll(Source, Target);
MoveAll(Source, Target);

RenameTo(Source, "NewName");


Additional Reading :
  1. MSDN Directory Info
  2. Move Folder Example
  3. Renaming Folder Example

C# File in Directory List

To Get List of File in directory. Sample Code:
 
//include this
using System.IO;

//set directory to scan
var dirInfo = new DirectoryInfo(@"C:\FolderName");

//checking if folder exists
if (dirInfo.Exists) {
    //*.* = get all file name
    FileInfo[] files = dirInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);   

    foreach (FileInfo file in files) {
        //example to list the file name using messagebox
        MessageBox.Show(file.ToString());
    }
}
Additional Reading at :
  1. MSDN DirectoryInfo
  2. MSDN GetFiles

Tuesday, January 1, 2013

C# Debug.Writeline

Debug.WriteLine is equivalent to Debug.Print in VB. Sample Code:
 

//include this
using System.Diagnostics;

//example
String Text = "Text Something";
Debug.WriteLine(Text);

C# ODP.NET Without Oracle Client

Required File:

where to download:
Oracle Website ODP.NET


How To Use:
 
//add reference Oracle.DataAccess to project

//include Oracle.DataAccess
using Oracle.DataAccess.Client;

//create connection string
string OraconnectionString = "user id=" + USERID + ";password=" + USERPASSWORD + ";" +
                                "data source=(DESCRIPTION=(ADDRESS=" +
                                "(PROTOCOL=tcp)(HOST=" + IPorSERVERNAME + ")" +
                                "(PORT=1521))(CONNECT_DATA=" +
                                "(SERVICE_NAME=" + ORACLESID + ")))";
//example Connection to DB
OracleConnection OraConnection = new OracleConnection(OraconnectionString);

try
{
    OraConnection.Open();
}
catch (OracleException err)
{
    OraConnection.Close();
}
finally
{
    OraConnection.Close();
}


//example insert/update/delete
OracleCommand OraCommand = new OracleCommand("", OraConnection);

if (OraConnection.State.ToString() == "Open")
{
    try
    {
        //sql command
        OraCommand.CommandText =
                "insert into " + table + " (" + field + ") values (" + data + ")";

        OraCommand.ExecuteNonQuery();

        OraCommand = null;

    }
    catch (OracleException ex)
    {
        return ex.Message.ToString();
    }
}
else
{
    return "Oracle Connection Close";
}


//example SQL select statement
string strSQL = "select COLUMN_NAME from TABLE";

//assign connection and sql statement
OracleCommand OraCommand2 = new OracleCommand(strSQL, OraConnection);
//create data reader
OracleDataReader OraDataReader = null;

if (OraConnection.State.ToString() == "Open")
{
    try
    {
        //execute data reader
        OraDataReader = OraCommand2.ExecuteReader();

        //read SQL result
        while (OraDataReader.Read() == true)
        {
            OraDataReader["COLUMN_NAME"].ToString();
        }

        OraDataReader.Close();

    }
    catch (OracleException ex)
    {
        ex.Message.ToString();
    }
}
else
{
    return "Oracle Connection Close";
}