Showing posts with label C# Windows Forms. Show all posts
Showing posts with label C# Windows Forms. Show all posts

Tuesday, October 6, 2009

C# Delegates


     
 If you click a Button on a form, the program would call a specific method. It is this pointer which is a delegate. Delegates are good because you can notify several methods that an event has occurred, if you so wish. The delegates are called as type safe because the signature of delegate must match the signature of the function the delegate points to.
A delegate is similar to class in that you create an instance of delegate and pass the function name as parameter to the the delegate constructor. It is this function that the delegate will point to.
A delegate signature is similar to the signature of a function except that delegate signature contains delegate key word

.Net is coming packed with EventHandler delegate. 
public delegate void EventHandler(object? sender, EventArgs e);
 It expects two parameters object and EventArgs. object can be used to inspect which control invoked the event handler. EventArgs represent the arguments of the event.
+= operator is user to wire up an Event handler to an event.

using System;
using System.Windows.Forms;
using System.Drawing;

class frmHello : Form
{
Button btn;
public static void Main()
{
Application.Run(new frmHello());
}
public frmHello()
{
this.Text = "shalvin.com";
btn = new Button();
btn.Location = new Point(50, 50);
btn.Text = "Hello";
btn.Click += new EventHandler(btn_Click);
this.Controls.Add(btn);
}
private void btn_Click(Object sender, EventArgs e)
{
MessageBox.Show("Welcome to C#");
}
}
















Delegate Inference


btnDelInf.Click += BtnDelInf_Click;
private void BtnDelInf_Click(object sender, System.EventArgs e)
{
    MessageBox.Show("Delegate Inference");
}

Mentioning the EvenHandler delegate along with event wiring is not not mandatory.


MenuStrip
using System;
using System.Windows.Forms;
using System.Drawing;

class frmHello : Form
{

MenuStrip menuStrip1;
ToolStripMenuItem fileToolStripMenuItem;
ToolStripMenuItem examplesToolStripMenuItem;
ToolStripMenuItem exitToolStripMenuItem;

public static void Main()
{
Application.Run(new frmHello());

}

public frmHello()
{
this.Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
this.menuStrip1 = new MenuStrip();
this.Controls.Add(menuStrip1);
fileToolStripMenuItem = new ToolStripMenuItem();
fileToolStripMenuItem.Text = "File";
menuStrip1.Items.Add(fileToolStripMenuItem);

examplesToolStripMenuItem = new ToolStripMenuItem();
examplesToolStripMenuItem.Text = "Examples";
menuStrip1.Items.Add(examplesToolStripMenuItem);

exitToolStripMenuItem = new ToolStripMenuItem();
exitToolStripMenuItem.Text = "Exit";
fileToolStripMenuItem.DropDownItems.Add("Exit");
}

}

ListBox


using System.Windows.Forms;
using System;
using System.Drawing;

namespace ConsoleApplication1
{
class Program : Form 
{
    Label lbl, lblStudents;
    TextBox txtName;
    Button btn;
    ListBox lstStudents;

    static void Main(string[] args)
    {
        Application.Run(new Program());
    }
    public Program()
    {
        this.Text = "Shavin.net";

        lblStudents = new Label { Text = "2012", Location = new Point(50, 50) };
        this.Controls.Add(lblStudents);

        lstStudents = new ListBox { Location = new Point(150, 50) };
        this.Controls.Add(lstStudents);

        lbl = new Label { Text = "Name", Location = new Point(50, 150) };
        this.Controls.Add(lbl);

        txtName = new TextBox{Location = new Point(150, 150)};
        this.Controls.Add(txtName);
       

        btn = new Button();
        btn.Text = "Add";
        btn.Location = new Point(100, 200);
        btn.Click +=new EventHandler(btn_Click);
        this.Controls.Add(btn);
    }
    private void btn_Click(object sender, EventArgs e)
    {
        lstStudents.Items.Add(txtName.Text);
        txtName.Text = "";
        txtName.Focus();
    }
}
}


Mono

Tuesday, July 28, 2009

Visual C# Express Edition 2008 IDE

C# is a modern object oriented programming language.I am going to have a series of blog on C# Windows forms. These series of blogs are intended to be the study material for my training sessions. So I might be following more of a tutorial walk through mode of blogging.




All the examples are based on Visual C# 2008 Express Edition which is a free development tool from Microsoft.




Fire up Visual Studio C# 2008 Express Edition. From the File menu select New Project. The New Project Dialog will appear, which will present you with different project types available in express edition. Note the WPF Application and WPF Browser Application project types which are new to 2008. This series of blogs are going to concentrate on windows forms applications, so select Windows Forms Applications and click Ok.



















You will be greeted with the IDE or Integrated Development Environment. Integrated Development Environment is the interface with which a programmer interacts with and develops application in Visual Studio.It comprises ofMenu Bar, ToolBar, ToolBox, Form Window, Properties Window, Solution Explorer, Code Windowand a host of other windows.If these windows are not visible by default you can navigate to View menu and select the window or use the short cut keys.

Its better to memorize short cut keys instead of using the mouse.
The short cut keys form various IDE components are as follows ToolBox (Ctrl Alt X), Properties Window (F4), Solution Explorer (Ctrl Alt L).

ToolBox
MenuBar and ToolBar requires no explanation. All windows users are very much familiar with MenuBar and ToolBar.

Just like a mechanic or electrician is having his own toolbox comprising of Screw drivers, testers, wires, etc. we .net programmers do have a toolbox with which we work. Toolbox is having a collection of controls.

Controls inside toolbox are arranged as tabs. Toolbox is having 8 tabs. The first tab All Windows Forms contains all the controls including containers, menus, data, components, printing and dialogs.

Common Controls tab contains commonly used controls Button, TextBox, Label, ListBox, ComboBox, etc.

Containers tab contains container controls. Container controls are those controls which acts as containers for other controls. This including simple containers like GroupBox, Panel and SplitContainers to complext containers like FlowLayoutPanel, TableLayoutPanel and TabControl.

Menus and Toolbars tab contains controls required for creating menus, context menus and toolbars.

Data tab contains controls required for database interaction.

Components tab contains those controls which doesn't have a visual interface at runtime. This includes controls like Timer, ErrorProvider, etc.

Printing tab contains print related controls like PrintPreviewDialog, PrintPreviewControl, PrintPreviewControls, etc.

Dialogs tab contains commonly used dialogs like OpenFileDialog, SaveFileDialog, ColorDialog, FontDialog, etc.

In addition to the existing tabs you can add your own tabs and controls to it. This feature comes handy for having a collection of COM controls or adding yours own controls to toolbox.



GroupBox Panel and TabControl
GroupBox Panel and TabControl

Group Box and Panel are container controls in Windows Forms. By container control I mean those controls which hosts other controls. These controls are used for logically group controls



















TabControl

A TabControl is used to have a collection of TabPages, thus avoiding the need for multiple forms as in the case with Windows Task Manager which can be invoked by pressing Ctl+Alt+Del. Here the functionalityn of 5 forms is incorporated in a single form.














Clicking the TabPages property in the properties window will invoke the TabPages Collection editor which can be used for adding Tab Pages.















private void btnDbNext_Click(object sender, EventArgs e)
{
tabControl1.SelectedIndex = 1;
}



shalvin.com

Windows Forms Input Validation

ErrorProvider Control Validating Event

MaxLength property of TextBox can be used to restrict the input lenght of the textbox to specified number.
Validating Event is used to check for the validity of data in the event of loosing focus from the control.

In the following example the user can't navigate away from the control unless he enters some value in the text box.

Make sure you give a visual indication to the error stating the error. In this case I am using an ErrorProvider Control for this purpose.

private void txtName_Validating(object sender, CancelEventArgs e)
{
if (txtName.Text == "")
{
e.Cancel = true;
errorProvider1.SetError(txtName, "Name cannot be blank");
}
else
errorProvider1.SetError(txtName, "");
}














Checking for Float values using float.TryParse

private void textBox1_Validating(object sender, CancelEventArgs e)
{
float num1;
bool res = float.TryParse(textBox1.Text, out num1);
if (res == false)
{
errorProvider1.SetError(textBox1, "only float is accepted");
}
else
{
errorProvider1.SetError(textBox1, "");
}
}



KeyDown event to Check for special keys
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt == true)
MessageBox.Show("Alt key pressed");
else if (e.Shift == true)
MessageBox.Show("Shift key pressed");
else if(e.Control == true)
MessageBox.Show("Contol key pressed");
else if (e.KeyCode == Keys.F1)
MessageBox.Show("F1 pressed");
}

WPF TextBox KeyDown Event
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftShift)
MessageBox.Show("Left shift key");
else if (e.Key == Key.RightShift)
MessageBox.Show("Right shift key");
else if (e.Key == Key.RightCtrl)
MessageBox.Show("Right Ctrl key");
else if (e.Key == Key.F1)
MessageBox.Show("F1 Key pressed");
}

KeyPress Event to Discern Character Keys

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}

KeyPress Event to Discard Non numeric input

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (! char.IsNumber(e.KeyChar))
e.Handled = true;
}

Discarding Lower Case Character
private void txtGrade_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsLower(e.KeyChar))
e.Handled = true;
}

Thursday, May 15, 2008

.Net Windows Forms Database Connectivity with Ado .Net

Database connectivity refers to the ability of an application to connect to database system in order to store, retrieve, update or delete data.

ADO.Net is a data access technology of .Net. ADO.Net contains Managed Providers and DataSet.

Managed providers provide libraries to connect to various databases.

 Two important Managed Providers are SqlClient and OleDb.

SqlClient namespace contains classes required for interacting with SQL Server.

OleDb is used to connect to any RDBMS say Oracle, Access and even SQL Server. 

But it is recommended using SqlClient with Sql Server, since SqlClient is tailor made for Sql Server. 

SqlConnection class is used for establishing a live session between front end and back end. 

In the connection string we specify the connection options like Database instance, security mode, etc.

Connection string is passed as a constructor to the SqlConnection. 

In this example we are using Integrated Security, ie. using the windows credential for connecting to SQL Server. 

 SqlDataReader is a read-only forward only recordset. 


In the SqlCommand's constructor we are passing the SqlCommand.

 

 Inorder to create an SqlDataReader the ExecuteReader method of SqlCommand have to be used.

SqlDataReader Read() Method
After creating the SqlDataReader we use the Read method for iterating throug the SqlDataReader and filling the ListBox.

using System.Data.SqlClient;

using System.Data.SqlClient;

SqlConnection cnn; 
SqlCommand cmd; SqlDataReader dr; 
private void Form1_Load(object sender, EventArgs e)
{
    cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind");
    cnn.Open();
    cmd = new SqlCommand("select * from Categories", cnn);
    dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        lstCategories.Items.Add(dr["CategoryName"].ToString());
    }
}




VB .Net

Imports System.Data.SqlClient 

 Dim cnn As New SqlConnection 

Dim cmd As SqlCommand 

Dim dr As SqlDataReader

 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

 cnn = New SqlConnection("integrated security=sspi;initial catalog=Northwind; 

data source=.\sqlExpress") 

cnn.Open() 

cmd = New SqlCommand("select* from categories", cnn) 

dr = cmd.ExecuteReader() 

While (dr.Read()) 

lstCategories.Items.Add(dr("categoryName")) 

End While 

End Sub


'









Inserting Records from Front End 

For inserting records use the ExecuteNonQuery() method of SqlCommand class. 


  
 using System.Data.SqlClient; 

SqlConnection cnn; SqlCommand cmd; 

 private void Form1_Load(object sender, EventArgs e) { 

cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Shalvin"); 

cnn.Open(); 

 private void btnInsert_Click(object sender, EventArgs e) { 

cmd = new SqlCommand("insert into Categories values ('Condiments')", cnn); cmd.ExecuteNonQuery(); 

MessageBox.Show("Record saved"); 

}

 

VB .Net

Imports System.Data.SqlClient

Dim cnn as SqlConnection Dim cmd as SqlCommand

Private Sub Form_Load(.. cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Shalvin") cnn.Open() End Sub

Private Sub btnInsert_Click(sender as object, e as EventArgs) .. cmd = new SqlCommand("insert into Categories values ('Condiments')", cnn)

cmd.ExecuteNonQuery() MessageBox.Show("Record saved") End Sub Connecting to Sql Server 2005 cnn = new SqlConnection("Data Source=.\\sqlexpress;Integrated Security=sspi;Initial Catalog=Shalvin"); <!-- #InsertTextBox Inserting values of TextBox The previous example cannot be used in real time since on clicking the button the same data will be inserted to the table. In this example we are constructing an Sql statement by concatenating the contents of TexBox as shown in the highlighted code. After inserting the values we blanking the control and bringing the focus back to the control. using System.Data.SqlClient; SqlConnection cnn; SqlCommand cmd; private void Form1_Load(object sender, EventArgs e) { cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Shalvin"); cnn.Open(); } private void btnInsert_Click(object sender, EventArgs e) { string strSql = "insert into Categories values ('" + txtCategoryName.Text + "')"; cmd = new SqlCommand(strSql, cnn); cmd.ExecuteNonQuery(); MessageBox.Show("Record saved"); BlankControls(); } private void BlankControls() { txtCategoryName.Text = ""; txtCategoryName.Focus(); } DataSet DataGrid DataSet is an offline disconnected data store.SqlDataAdapter is an intemediary between the RDBMS and DataSet. The methods of SqlDataAdapter are Fill and Update. Fill Method is used for filling a DataSet. Update Method is used synchronizing the RDBMS with changes in DataSet. using System.Data.SqlClient; SqlConnection cnn; SqlDataAdapter da; DataSet ds = new DataSet(); private void Form1_Load(object sender, EventArgs e) { cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Shalvin"); da = new SqlDataAdapter("select * from Categories", cnn); da.Fill(ds, "Shalvin"); dataGridView1.DataSource = ds.Tables["Shalvin"]; }

VB .Net

Imports System.Data Imports System.Data.SqlClient Public Class frmGrid Dim cnn As SqlConnection Dim ds As New DataSet Dim da As SqlDataAdapter Private Sub frmGrid_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cnn = New SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind") cnn.Open() da = New SqlDataAdapter("select * from Categories", cnn) da.Fill(ds, "Cat") DataGridView1.DataSource = ds.Tables("Cat") End Sub End Class

DataSet with Multiple DataTables A DataSet is a collection of DataTables along with other objects just like Database is a collection of Tables (views, stored procedures, etc.). This example requires DataGrid insted of GridView Control.

using System.Data.SqlClient; SqlConnection cnn; SqlDataAdapter da; DataSet ds = new DataSet(); private void Form1_Load(object sender, EventArgs e) { cnn = new SqlConnection("Integrated security=sspi;Initial Catalog=Northwind"); da = new SqlDataAdapter("select CategoryId, CategoryName, Description from categories", cnn); da.Fill(ds, "Cat"); da = new SqlDataAdapter("select ProductId, ProductName, UnitPrice from Products", cnn); da.Fill(ds, "Prod"); dataGrid1.DataSource = ds; }

VB .Net

Imports System.Data Imports System.Data.SqlClient Public Class frmGrid Dim cnn As SqlConnection Dim ds As New DataSet Dim da As SqlDataAdapter Private Sub frmGrid_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cnn = New SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind") cnn.Open() da = New SqlDataAdapter("select CategoryId, CategoryName, Description from Categories", cnn) da.Fill(ds, "Cat") da = New SqlDataAdapter("select ProductId, ProductName, UnitPrice from Products", cnn) da.Fill(ds, "Prod") DataGrid1.DataSource = ds End Sub

DataTable DataColumn and DataRow Visit http://shalvinpd.blogspot.com/2008/03/datatable-datacolumn-and-datarow-aspnet.html for Asp.net code of DataTable DataColum and DataRow. DataSet is an offline disconnected Data Store. DataSet is a collection of DataTables. A DataTable Contains DataRow and DataColumns. The following code illustrating creating DataTable, DataRow and DataColumn. This approached can be used for creating a temporary storage of structured data. DataTable dt = new DataTable("Purchase"); DataColumn dc; DataRow dr; private void Form1_Load(object sender, EventArgs e) { dc = new DataColumn("ProductName"); //Adding the column to the Columns colluction of DataTable dt.Columns.Add(dc); dc = new DataColumn("Price"); //Adding the column to the Columns colluction of DataTable dt.Columns.Add(dc); //Adding a new row to the table dr = dt.NewRow(); dr["ProductName"] = "Microsoft Mouse"; dr["Price"] = 400; dt.Rows.Add(dr); dgPurchase.DataSource = dt; } Creating AutoIncrement Colum for DatTable Just like Sql Server is having an identity column, we can have an auto increment column for out datatable. Set the AutoIncrement property of column to true you can optionally set the AutoIncrementSeed and AutoIncrementStep. DataTable dt = new DataTable("Purchase"); DataColumn dc; DataRow dr; private void Form1_Load(object sender, EventArgs e) { dc = new DataColumn(("Product ID"), System.Type.GetType("System.Int32")); dc.AutoIncrement = true; dc.AutoIncrementSeed = 100; dc.AutoIncrementStep = 1; dt.Columns.Add(dc); dc = new DataColumn("ProductName"); dt.Columns.Add(dc); dc = new DataColumn("Price"); dt.Columns.Add(dc); dr = dt.NewRow(); dr["ProductName"] = "Microsoft Mouse"; dr["Price"] = 400; dt.Rows.Add(dr); dr = dt.NewRow(); dr["ProductName"] = "Shalvin's C# Tutorial Video"; dr["Price"] = 4000; dt.Rows.Add(dr); dgPurchase.DataSource = dt; }

DataSet and ComboBox's DisplayMember Property

Combox's DisplayMember property is used to specify the column to display in a ComboBox.

using System.Data.SqlClient; SqlConnection cnn; SqlDataAdapter da; DataSet ds = new DataSet(); private void Form1_Load(object sender, EventArgs e) { cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind"); da = new SqlDataAdapter("select CategoryId, CategoryName, Description from Categories", cnn); da.Fill(ds, "Cat"); cboCategories.DataSource = ds.Tables["Cat"]; cboCategories.DisplayMember = "CategoryName"; }

Login Module in Windows Forms Table and Stored Procedure create table UserTable (UserId int identity(1,1) primary key, RoleId int, UserName varchar(20), Password varchar(20)) create procedure spusertable(@pMode char(1), @pUserId int = null, @pRoleId int = null, @pUserName varchar(20) = null,@ppassword varchar(20) = null) as if @pMode = 'S' select * from Usertable else if @pMode = 'I' insert into usertable values(@pRoleid,@pUsername,@ppassword) else if @pmode='D'delete from usertable where userid=@puserid go Windows Forms SqlConnection cnn; SqlCommand cmd; SqlDataReader dr; int count; private void btnLogin_Click(object sender, EventArgs e) { cmd = new SqlCommand("select count(*) from usertable where UserName = '" + txtUserName.Text + "'and password = '" + txtPassword.Text + "'", cnn); count = Int32.Parse(cmd.ExecuteScalar().ToString()); if (count != 0) { frmMain fm = new frmMain(); fm.Show(); this.Hide(); } else MessageBox.Show("Invalid User"); } }