Wednesday, July 29, 2009

Visual Studio .Net Setup Wizard Screenshots





















WMI : Extracting Installed Product Information of another machine

For this example to work you should set a reference to System.Management.

using System.Management;

private void Form1_Load(object sender, EventArgs e)
{
ConnectionOptions DemoOptions = new ConnectionOptions();
DemoOptions.Username = "admin";
DemoOptions.Password = "admin";
ManagementScope DemoScope = new ManagementScope("\\\\indiaop1\\root\\cimv2", DemoOptions);
ObjectQuery DemoQuery = new ObjectQuery("select * from win32_Product");
ManagementObjectSearcher DemoSearcher = new ManagementObjectSearcher(DemoScope, DemoQuery);
ManagementObjectCollection AllObjects = DemoSearcher.Get();
foreach (ManagementObject DemoObject in AllObjects)
listBox1.Items.Add(DemoObject["Caption"].ToString());
}

String Formatting Resources

http://blog.stevex.net/index.php/string-formatting-in-csharp/

Query Analyser with C# Beta

































I am not basically a fan of Sql Server 2005 Management Studio mainly because of its compatibility issues and high overhead.


So I thought of creating a simple query tool. Here is the code.




using System.Data.SqlClient;
namespace TreeView_in_Split_Container
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection cnn, cnn2;
SqlCommand cmd;
SqlDataReader dr, dr2;
List<string> glsdb = new List<string>();
string strDbCnn;
private void Form1_Load(object sender, EventArgs e)
{
cnn = new SqlConnection(@"integrated Security=sspi;Initial Catalog=master;Data Source=.\sqlexpress");
cnn.Open();
cmd = new SqlCommand("sp_helpdb",cnn);
dr = cmd.ExecuteReader();
treeView1.Nodes.Add("Database");
while (dr.Read())
{
glsdb.Add(dr["Name"].ToString());
treeView1.TopNode.Nodes.Add(dr["Name"].ToString());
comboBox1.Items.Add(dr["Name"].ToString());
}
dr.Close();
}





Database Combo Selection
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
cnn = new SqlConnection(@"integrated Security=sspi;Data Source=.\sqlexpress;Initial Catalog=" + comboBox1.Text );
cnn.Open();
}


Object Browser


The project make use of two Context Menu dataContext and contextMenuStrip1. First for database related options like Create Database whose functionality is yet to be implemented. second for table related options like Show Table Data.






private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
try
{
TreeNode tempNode = treeView1.GetNodeAt(e.X, e.Y);
treeView1.SelectedNode = tempNode;
if (treeView1.SelectedNode.Level == 1)
{
treeView1.ContextMenuStrip = null;
strDbCnn = (@"integrated Security=sspi;Data Source=.\sqlexpress;Initial Catalog=" + tempNode.Text);
cnn2 = new SqlConnection(strDbCnn);
cnn2.Open();
cmd = new SqlCommand("select * from sysobjects where xtype = 'u'", cnn2);
dr2 = cmd.ExecuteReader();
treeView1.SelectedNode.Nodes.Clear();
while (dr2.Read())
{
treeView1.SelectedNode.Nodes.Add(dr2[0].ToString());
}
cnn2.Close();
dr2.Close();
}
else if (treeView1.SelectedNode.Level == 0)
{
treeView1.ContextMenuStrip =DataContext;
}
else if (treeView1.SelectedNode.Level == 2)
{
treeView1.ContextMenuStrip = contextMenuStrip1;
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}



Execute Button Click Code
private void button1_Click(object sender, EventArgs e)
{
try
{
string strSql = "";
if (textBox1.SelectedText != "")
strSql = textBox1.SelectedText;
else
strSql = textBox1.Text;

string strtmp = strSql;
string[] ss = strSql.Split(new char[]{' '});

if(ss[0].Equals("Use"))
{
richTextBox1.Text = "Database context changed to" + ss[1];
return;
}


cmd = new SqlCommand(strSql, cnn);
dr = cmd.ExecuteReader();
richTextBox1.Text = "";
int irf = dr.RecordsAffected;
while (dr.Read())
{

for (int i = 0; i < dr.FieldCount; i++)
{

richTextBox1.Text += dr[i].ToString() + "\t";

}

richTextBox1.Text += "\n";


}
if (irf > 0)
{
richTextBox1.Text += irf + " records affected";
}
dr.Close();
}
catch (Exception ex)
{
richTextBox1.Text += ex.Message.ToString();
}
}



Showing the SELECT result in Grid View


private void showDataToolStripMenuItem_Click(object sender, EventArgs e)
{

DataGrid d1 = new DataGrid();
d1.Dock = DockStyle.Fill;
cnn2 = new SqlConnection(strDbCnn);
cnn2.Open();
SqlDataAdapter adp;
adp = new SqlDataAdapter("select * from " + treeView1.SelectedNode.Text, cnn2);
DataSet ds=new DataSet();
adp.Fill(ds,"T1");
d1.DataSource = ds.Tables["T1"];
cnn2.Close();

splitContainer2.Panel2.Controls.Add(d1);
d1.BringToFront();
}




Windows Generated Code



private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.splitContainer2 = new System.Windows.Forms.SplitContainer();
this.textBox1 = new System.Windows.Forms.TextBox();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.btnExecute = new System.Windows.Forms.Button();
this.treeView1 = new System.Windows.Forms.TreeView();
this.label1 = new System.Windows.Forms.Label();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.DataContext = new System.Windows.Forms.ContextMenuStrip();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip();
this.createDatabaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showDataToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.panel1.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout();
this.splitContainer2.SuspendLayout();
this.DataContext.SuspendLayout();
this.contextMenuStrip1.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.panel1.Controls.Add(this.comboBox1);
this.panel1.Controls.Add(this.label1);
this.panel1.Controls.Add(this.btnExecute);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(529, 77);
this.panel1.TabIndex = 0;
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 77);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.treeView1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.splitContainer2);
this.splitContainer1.Size = new System.Drawing.Size(529, 286);
this.splitContainer1.SplitterDistance = 176;
this.splitContainer1.TabIndex = 1;
//
// splitContainer2
//
this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer2.Location = new System.Drawing.Point(0, 0);
this.splitContainer2.Name = "splitContainer2";
this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer2.Panel1
//
this.splitContainer2.Panel1.Controls.Add(this.textBox1);
//
// splitContainer2.Panel2
//
this.splitContainer2.Panel2.Controls.Add(this.richTextBox1);
this.splitContainer2.Size = new System.Drawing.Size(349, 286);
this.splitContainer2.SplitterDistance = 95;
this.splitContainer2.TabIndex = 0;
//
// textBox1
//
this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBox1.Location = new System.Drawing.Point(0, 0);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(349, 95);
this.textBox1.TabIndex = 0;
//
// richTextBox1
//
this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox1.Location = new System.Drawing.Point(0, 0);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(349, 187);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// btnExecute
//
this.btnExecute.Location = new System.Drawing.Point(80, 10);
this.btnExecute.Name = "btnExecute";
this.btnExecute.Size = new System.Drawing.Size(75, 23);
this.btnExecute.TabIndex = 1;
this.btnExecute.Text = "&Execute";
this.btnExecute.UseVisualStyleBackColor = true;
this.btnExecute.Click += new System.EventHandler(this.btnExecute_Click);
//
// treeView1
//
this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView1.Location = new System.Drawing.Point(0, 0);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(176, 286);
this.treeView1.TabIndex = 0;
this.treeView1.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseClick);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(185, 20);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(86, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Select Database";
//
// comboBox1
//
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(277, 10);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 21);
this.comboBox1.TabIndex = 3;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// DataContext
//
this.DataContext.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.createDatabaseToolStripMenuItem});
this.DataContext.Name = "DataContext";
this.DataContext.Size = new System.Drawing.Size(157, 26);
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.showDataToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(153, 48);
//
// createDatabaseToolStripMenuItem
//
this.createDatabaseToolStripMenuItem.Name = "createDatabaseToolStripMenuItem";
this.createDatabaseToolStripMenuItem.Size = new System.Drawing.Size(156, 22);
this.createDatabaseToolStripMenuItem.Text = "Create Database";
//
// showDataToolStripMenuItem
//
this.showDataToolStripMenuItem.Name = "showDataToolStripMenuItem";
this.showDataToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.showDataToolStripMenuItem.Text = "Show Data";
this.showDataToolStripMenuItem.Click += new System.EventHandler(this.showDataToolStripMenuItem_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(529, 363);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.panel1);
this.Name = "Form1";
this.Text = "Shalvin Sql Server Management Studio";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.Form1_Load);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.splitContainer2.Panel1.ResumeLayout(false);
this.splitContainer2.Panel1.PerformLayout();
this.splitContainer2.Panel2.ResumeLayout(false);
this.splitContainer2.ResumeLayout(false);
this.DataContext.ResumeLayout(false);
this.contextMenuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
}
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.SplitContainer splitContainer2;
private System.Windows.Forms.Button btnExecute;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.TreeView treeView1;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ContextMenuStrip DataContext;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem createDatabaseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem showDataToolStripMenuItem;

Tuesday, July 28, 2009

WPF Menu

Tweaking the raw Xaml is not needed in the new editions of Visual Studio.

This blog assumes that you are familiar with Xml. If not view my blog Working with Xml.

To Start with I am creating a Menu with a MenuItem called File and below that two MenuItems File, Exit and a Separator in between. It is very much possible to construct a menu with the Menu control and Properties window.

<Menu>


<MenuItem Name="mnuFile" Header="_File">


<MenuItem Name="mnuNew" Header="_New"/>


<Separator/>


<MenuItem Name="mnuExit" Header="_Exit"/>


</MenuItem>


</Menu>

Adding Event Handler to Menu








Pressing the tab key automatically created an event handler.

private void mnuExit_Click(object sender, RoutedEventArgs e)
{
Close();
}

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

Asp .Net and Visual Web Developer Express Edition

Asp .Net is Microsoft's Web Application Framework meant for developing dynamic web sites and web Services.

Visual Web Developer Express Edition is the free web developement tool from Microsoft. This series of lessons are based on Visual Web Developer Express Edition. The examples will work perfectly fine in Visual Studio .Net.

Asp .Net Introduction and Button Control








Start Visual Web Developer or Visual Studio. Start a new project by selecting File, New Web Site.
Select Asp .Net Web site as shown in the figure below.


















You will be greeted with the IDE (Integrated Developement). The IDE is very similar to other Visual Studio IDEs.























Inorder to add a control to the form double click on the control in the toolbox. Add a button to the form by double clicking a button in the toolbox. Set its id property to btnHello and Text Property to Hello

Double click on the button to go to the Button's Click event in the code window.
Asp .Net supports both Code Behind and Inline mode for coding. In Code Behing mode a separate file is created which will be holding the code. So if the asp .net page is Default.aspx another file called Default.asp.cs page will be holding the code.

Code behind is the preferred mode for coding. I will take up inline mode in a later blog.

Add the following code :


protected void btnHello_Click(object sender, EventArgs e)
{
Response.Write("Hello welcome to Asp .Net");
}

Now run the application by either clicking the run button or pressing F5. On clicking the button you will receice the Hello message as shown in the figure below.















Asp .Net TextBox

HTML (Hypertext Markup Language)

Html is the language of web. It is a tag based language.





Result





Title
Title tag is used to produce a title for the document. The title appears in the title bar of Browser.








Result
















Br



Br tag is used for producing a break between contents







Result




H1 and H2







BgColor Attribute






Unordered List




Ordered List

ColorDialog and FontDialog in .Net Windows Forms

ColorDialog displays a list of colors and returns a property containing the selected color.
FontDialog enables the user to select a font and set its properties such as size, style, etc.























All the dialog boxes in .Net (ColorDialog, FontDialog, FolderBrowserDialog, FontDialog, PageSetupDialog and PrintDialog) inherit from System.Windows.Forms.CommonDialog class.

The ShowDialog method of CommonDialog class is used for running a dialog. We are also checking whether the Ok button is dialog is selected. If so we are changing the Back ground color of the form in the case of first button and the font the whole form in the case of second button.

private void btnColor_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
this.BackColor = colorDialog1.Color;
}

private void btnFont_Click(object sender, EventArgs e)
{
if (fontDialog1.ShowDialog() == DialogResult.OK)
this.Font = fontDialog1.Font;
}

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;
}

Windows Forms ListView



ListView is a very important control in Windows Forms. ListView can be used to display complex data list employee information, file information and the like.
You can see a list view in action in the Windows Explorer's right hand side.
Listview comes with various Views like SmallIcon, LargeIcon, Tile, List and Detail.

In this blog I am going to concentrate on DetailsView.

private void Form1_Load(object sender, EventArgs e)
{
listView1.View = View.Details;









//Adding Columns
listView1.Columns.Add("Blogs", 170);
listView1.Columns.Add("Blogger" , 100);












//Adding a ListView Item
ListViewItem item1 = new ListViewItem("shalvin.com", 0);
item1.SubItems.Add("Shalvin P D");
listView1.Items.Add(item1);
ListViewItem item2 = new ListViewItem("shalvinpd.blogspot.com", 0);
item2.SubItems.Add("Shalvin P D");
listView1.Items.Add(item2);
}








First I am adding Header to ListBox using Columns.Add method passing in the HeaderName and width.
Then I am adding items to ListView using ListViewItem Class which represents an item in ListView and then adding the SubItem to ListView using Items.Add.






























It is possible to change the look of in item in ListView using the ListViewItem class :

Font f = new Font(FontFamily.GenericSerif, 10, FontStyle.Bold ^ FontStyle.Italic);
item1.BackColor = Color.LightBlue;
item1.Font = f;
listView1.Items.Add(item1);

























Working with ListView Visually



Oracle Connectivity from C# Windows Forms

Inserting Values from Front End

System.Data.OleDb namespace contains classes required for interacting with any RDBMS including Oracle.

OleDbConnection class is used for establishing a live session between front end and back end. In this example we are connecting to Oracle with scott as username, tiger as password and hostname is Shalvin.

using System.Data.OleDb;



OleDbConnection cnn;
OleDbCommand cmd;
private void Form1_Load(object sender, EventArgs e)
{
cnn = new OleDbConnection("provider=msdaora.1;user id=scott;password=tiger;Data Source=Cargomar");
cnn.Open();
}
private void btnInsert_Click(object sender, EventArgs e)
{
cmd = new OleDbCommand("insert into Categories values (5, 'Mouse', 'Computer Mouse')", cnn);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Saved");
}




Filling TextBox based on Selection from ComboBox

A common programming task is obtaining the details of a record based on a selection. Here Initially I am filling a combo box with Category Names. Based on a selection from Combo Box the the details of the Category will be displayed on the text boxes.










using System.Data.OleDb;

OleDbConnection cnn;
OleDbDataAdapter da;
DataSet ds = new DataSet();

bool b = false;

OleDbCommand cmd;
OleDbDataReader dr;

private void Form1_Load(object sender, EventArgs e)
{
cnn = new OleDbConnection("Provider=msdaora;Data Source=Cargomar;user id=scott;password=tiger");

cnn.Open();
da = new OleDbDataAdapter("select * from Categories", cnn);
da.Fill(ds, "Cat");
cboCategoryName.DataSource = ds.Tables["Cat"];
cboCategoryName.DisplayMember = "CategoryName";
cboCategoryName.ValueMember = "CategoryId";
b = true;
}

private void cboCategoryName_SelectedIndexChanged(object sender, EventArgs e)
{
if (b)
{
cmd = new OleDbCommand("select * from Categories where categoryId = " + cboCategoryName.SelectedValue, cnn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
txtCategoryId.Text = dr["CategoryId"].ToString();
txtDescription.Text = dr["Description"].ToString();
}
}

Deleting Record
private void btnDelete_Click(object sender, EventArgs e)
{
cmd = new OleDbCommand("delete from Categories where CategoryId = " + cboCategoryName.SelectedValue, cnn);
cmd.ExecuteReader();
MessageBox.Show("Record Deleted");
}

Editing Record

private void btnEdit_Click(object sender, EventArgs e)
{
txtCategoryId.Enabled = false;
cmd = new OleDbCommand("Update Categories set Description = '" + txtDescription.Text + "' where CategoryId = " + cboCategoryName.SelectedValue, cnn);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Edited successfully");
}

VB.Net

Imports System.Data.SqlClient

Dim cnn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As New DataSet

Dim b As Boolean = False
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")
cnn.Open()
da = New SqlDataAdapter("select * from Categories", cnn)
da.Fill(ds, "Cat")
cboCategories.DataSource = ds.Tables("Cat")
cboCategories.DisplayMember = "CategoryName"


cboCategories.ValueMember = "CategoryId"

b = True
End Sub

Private Sub cboCategories_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCategories.SelectedIndexChanged
If b = True Then

Dim strSql As String
strSql = "select * from Categories where CategoryId = " + cboCategories.SelectedValue.ToString()
cmd = New SqlCommand(strSql, cnn)
dr = cmd.ExecuteReader
While (dr.Read())
txtCategoryId.Text = dr("CategoryId")
txtDescription.Text = dr("description")
End While
dr.Close()
End If

End Sub

Enumerations in C#

Enumerations are the mechanism to group related constants. System.Enum class provides the base class for enumerations, it is a value type.
The following example demonstrates using WindowState enum in WPF. In the case of WindowState enumerator there are three constants viz., Maximized, Minimized and Normal.









Creating Enumerations
In the following example I am creating an enum called Tech with three constants Wpf, Silverlight and Xbap and later on I am using using it. Extensive use of enums makes your code more consistent.

enum TEch
{
Wpf, Silverligh, Xbap
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show(TEch.Silverligh.ToString());
}

The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.

In the following example I am extracting the value of the element Wpf.


private void Window_Loaded(object sender, RoutedEventArgs e)
{
int i = (int)TEch.Wpf;
MessageBox.Show(i.ToString());
}


When you run the application you will get 0. If you substitute Wpf with Silverlight or Xbap you will get 1 or 2 respectively.


It is possible to alter the default underlying value by assigning another values.

enum TEch
{
Wpf = 2, Silverligh = 4, Xbap = 6
}









Enum.GetValues() method
Enum.GetValues() method to extract the constants in an Enumeration.
using System.Drawing;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
KnownColor [] color = (KnownColor[])Enum.GetValues(typeof(KnownColor));
foreach (KnownColor colorName in color)
{
listBox1.Items.Add(colorName);
}
}



For this example to work in WPF you should set reference to System.Drawing

WPF Colors

The Brushes class provides 141 colors.

private void btnColor_Click(object sender, RoutedEventArgs e)
{
this.Background = Brushes.Red;
}


You can also have a wide ranging colors using the combination of Red, Green and Blue.

private void btnGreen_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromRgb(0, 255, 0));
}

In the previous I am creating Green color by assigning 255, the maximum value to Green component, ie. the second parameter


private void btnWhite_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromRgb(255, 255, 255));
}

private void btnYellow_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromRgb(255, 255, 0));
}

Grey Scale
private void btnWhite_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
}

private void btnBlack_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
}

private void btnDarkGrey_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 50, 50, 50));
}

private void btnMGrey_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 150,150, 150));
}

private void slider1_ValueChanged(object sender,

RoutedPropertyChangedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255,

(byte)slider1.Value, (byte)slider1.Value, (byte)slider1.Value));
}


LinearGradientBrush
LinearGradientBrush displays a gradualy changing mix of two or more color schemes.
The surface where you are planning to draw the linear gradient is considered to he unit 1 wide and 1 unit high.


private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Background = new LinearGradientBrush(Colors.Red, Colors.Blue, new Point(0, 0), new Point(1, 1));
}


LinearGradientBrush the Coded way


using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WPFBrush
{
class Class1 : Window
{
[STAThread]
public static void Main()
{
Application app = new Application();
app.Run(new Class1 { Title = "Shalvin - Colors" });
}
public Class1()
{
Grid LayoutRoot = new Grid();
this.Content = LayoutRoot;
LayoutRoot.Background = new LinearGradientBrush(Colors.Red, Colors.Blue, 0);
}
}
}


RadialGradientBrush

Grid LayoutRoot = new Grid();
this.Content = LayoutRoot;
LayoutRoot.Background = new RadialGradientBrush (Colors.Red, Colors.Blue);


RadialGradientBrush and GradientStops


RadialGradientBrush brush = new RadialGradientBrush();
Background = brush;
brush.GradientStops.Add(new GradientStop(Colors.Red, 0));
brush.GradientStops.Add(new GradientStop(Colors.Green, .33));
brush.GradientStops.Add(new GradientStop(Colors.Blue, .66));

WPF (Windows Presentation Foundation)

This is a beginner level blog on WPF.


Nesting Controls
Styles
Exploring WPF the Code Way

Majority of examples presented in this blog will work with Silverlight also.
Windows Presentation Foundation (WPF) is the Microsoft's presentation technology for creating compelling user interface including graphics and media.
It is based on Vector Graphics
Create a new project in Visual Studio 2008 by selecting File, New Project.
Starting a WPF Application Project

















The WPF editor contains two view the visual representation of the form as well as the XAML implementation of the window.

A WPF Form is in fact a class that inherits from System.Windows.Window. The Window class which in turn inherits from ContentControl class.A ContentControl class can have only a single element as its Content Property.
Inside the Windows is a Grid Control that can hold multiple child controls.









As you set the propeties of an element both the windows designer as well as the xaml gets updated.







Here I am settting the Title for the form.






























You can also edit the xaml and the changes will be immediately apparent in the windows designer.





















Setting the window title at Runtime

private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Title = "shalvinpd.blogspot.com";
}




WPF do have a collection of common control which you would expect in a presentation technology.

















Button

Drag and drop a button on to the windows design surface.




























On clicking the button you will be taken to the event handler.


private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello welcome to WPF", "Shalvin.com");
}

Run the application. Click on the button and you will receice a welcome message.


















MessageBox.Show Method's Overloads

MessageBox's Show method has 21 overloads, following are a few examples.

private void btnHello_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello");
}

private void btnHelloCaption_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello", "shalvin");
}

private void btnYesNo_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello", "Shalvin", MessageBoxButton.YesNo);
}

private void btnExclamation_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello", "Shalvin", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
}

MessageBoxResult
private void btnClose_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Do you want to quit ?", "Shalvin", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
Close();
}

String Memory Variable

private void btnMemoryVariable_Click(object sender, RoutedEventArgs e)
{
string strName = "Shalvin";
MessageBox.Show("Hello " + strName);
strName = "Shalvin P D";
MessageBox.Show("Hello " + strName);
}


String Concatenation
In this example instread of simply displaying a Hello message the user will be greated with the name entered in text box.













private void button1_Click(object sender, RoutedEventArgs e)

{
MessageBox.Show("Hello " + txtName.Text);
}




















Integer Memory Variable and Simple Calculator




















int i, j, res;
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
i = Int32.Parse(txtInt1.Text);
j = Int32.Parse(txtInt2.Text);
res = i + j;
lblResult.Content = res.ToString();
}

Here I am defining three integer memory variables i, j and res. Int32.Parse() method is used to convert the textbox data to integer.

<Window x:Class="WpfApplication1.Calc"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Calc" Height="300" Width="300" Loaded="Window_Loaded">
    <Grid>
        <Label Content="Integer 1" Height="28" HorizontalAlignment="Left" Margin="44,33,0,0" Name="label1" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="120,33,0,0" Name="txtInt1" VerticalAlignment="Top" Width="120" />
        <Label Content="Integer 2" Height="28" HorizontalAlignment="Left" Margin="53,88,0,0" Name="label2" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="120,80,0,0" Name="txtInt2" VerticalAlignment="Top" Width="120" />
        <Label Content="Result" Height="28" HorizontalAlignment="Left" Margin="63,132,0,0" Name="label3" VerticalAlignment="Top" />
        <Label Height="28" HorizontalAlignment="Left" Margin="120,132,0,0" Name="lblResult" VerticalAlignment="Top" Width="112" BorderBrush="Black" BorderThickness="1" />
        <Button Content="+" Height="23" HorizontalAlignment="Left" Margin="98,196,0,0" Name="btnAdd" VerticalAlignment="Top" Width="75" Click="btnAdd_Click" />
    </Grid>
</Window>

ListBox

ListBox is used for displaying a number of items at the same time. Place a ListBox on to the form and select the Items collection from the properties window. The Collection Editor dialog will appear. You can add additional items to the ListBox by clicking the Add button and specifying a Content.






Behing the scene it will create ListBoxItems tags inside the ListBox tag.







It is possible to add items to ListBox at runtime. Double click on the title of the form and you will be taken to the Loaded event of the Window.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
lstInterests.Items.Add("Guitar");
}





ComboBox
ComboBox contains similar functionality that of ListBox. Above mentioned functionality also works with ComboBox

RadioButton and If else











private void btnGender_Click(object sender, RoutedEventArgs e)
{
if (rbMale.IsChecked == true)
MessageBox.Show("Male candidate");
else
MessageBox.Show("Female candidate");
}













DatePicker Control
private void btnDate_Click(object sender, RoutedEventArgs e)
{
DateTime dt = DateTime.Parse(datePicker1.SelectedDate.ToString());
MessageBox.Show(dt.ToString());
MessageBox.Show(dt.ToString("d"));
MessageBox.Show(dt.ToString("D"));
}

Nesting Controls

































As usual you can have event handlers of the controls. In this case I am extracting the value of Inner TextBox, concatenating it with a Hello and MessageBoxing it.

private void btnHello_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello " + txtName.Text);
}























































Styles
Styles as WPF equivalent of CSS in Html.


















Working with Styles at Runtime




private void btnBold_Click(object sender, RoutedEventArgs e)
{
btnBold .Style = (Style)FindResource("BoldStyle");
}








Filling Wpf ComboBox with the Contents of a SqlDataReader
using System.Data.SqlClient;
SqlConnection cnn = new SqlConnection(@"Integrated Security=sspi;Initial Catalog=Shalvin;Data Source=.\sqlexpress");
SqlCommand cmd;
SqlDataReader dr;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cnn.Open();
cmd = new SqlCommand("select * from Categories", cnn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
cboCategories.Items.Add(dr["CategoryName"]);
}
}























Exploring WPF the Code Way
Having seen the fundamentals of working with IDE. Let's turn out attention to the internals of WPF in coded way, means without XAML.

using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
class Class1 : Window
{
[STAThread]
public static void Main()
{
Application app = new Application();
app.Run(new Class1{Title = "shalvin"});
}
public Class1()
{
Grid LayoutRoot = new Grid();
this.Content = LayoutRoot;
Button btn = new Button();
btn.Width = 75;
btn.Height = 50;
btn.Content = "Hello";
LayoutRoot.Children.Add(btn);
}
}
}