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();
}
Tuesday, July 28, 2009
WPF Menu
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. Almost all the sites in the web is created using HTML. It is a tag based language.
HTML can be created with plain Notepad or a there are a slew of editors like Visual Studio Code, Atom, Sublime, etc. I am using Notepad to start with.
An HTML document contained two main section viz. Head section and Body section. Body section is where the contents of the page will appear. The Head section contains information like Title of the Page, Scripts, etc.
<html>
<body>
Shalvin P D
</body>
</html>
There are both opening and closing tags. Closing tag is denoted by /. Eg. </html>, </body>, etc. Notice that I have indented the tags so that it will be more readable. The relationship between tags can be better understood with indentation. Here HTML is the parent tag.
I saved the document with .htm extension. Double clicking on the file will open the html document inside the default browser.
The Browser will interpret the HTML tags and produce the web site.
Title Title tag is used to produce a title for the document. The title appears in the title bar of Browser.
<html>
<head>
<title>.Net and Angular Consultant and Trainer</title>
<head>
<body>
Shalvin P D
</body>
</html>
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
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.
Font f = new Font(FontFamily.GenericSerif, 10, FontStyle.Bold ^ FontStyle.Italic);
item1.BackColor = Color.LightBlue;
item1.Font = f;
listView1.Items.Add(item1);
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
