You are on page 1of 43

Session.

C# Programming
.NET Interoperatibility , Windows Forms,
Database Programming

RCW (Runtime Callable Wrappers)


- When you have created a COM component in VB VC++ Java or any unmanaged code it can be easily reusable into .NET platform; when in .net application you can reuse the COM component By right click on Add reference and you can click on COM and you find the registered component of unmanaged application registered on your machine o/s. - .NET internally makes use of utility tool called tlbimp that does the conversion and allows access of COM in .NET Com hence called as interoperatibility. ACOM-------Registered O/s----------------.NET Platform-----------------TLBIMP

VB VB ASP.NET C++ VC++ Java

C# (Conversion)

- CCW (Com Callable Wrappers) When you create assembly component in .net environment in order to support assembly to work with unmanaged code first add attribute in assembly info to make comvisible attribute true and KeyAttribute with strong key and build it, and then add to GAC; - After that use the console command tlbexp in the directory where the .dll file is created and

this will produce the Type Library file tlb file and then in order to use with unmanaged code we have to register the assembly using the regasm to use with windows

Windows Forms: A graphical user interface for

building windows client application that uses the CLR its the name given for GUI that constitutes part of microsoft .net framework;

- Creating Windows Forms: when creating win forms create certain files form1.cs and designers code and program.cs and resources.resx and then you can add controls and do event driven GUI application You can change title with text with its properties and formatborderstyle property to resize or fixed Display and hiding controls of windows min max and close buttons using controlbox property or use individual property for max and min button; and position the form using startposition;

Multiple Forms: You can add multiple forms and communicate between them and setting up startup form. FORM2

FORM 1 Calling Form: drag and drop a textbox and button on click it communicates with another form

Application------|-----Form Manages: run/exit | Controls Low level behavior


class Form1 :System.Windows.Forms.Form { . [STAThread] static void Main() { Application.Run(new frmObject()); } . }

You can communicate with MessageBox and inputbox apart from that you can create your custom dialog box using form that you add to your application by changing some of the important properties; and also custom code using runtime code for creating controls runtime for console application to support forms you have to add reference Sytem.Windows.Forms and System.Drawing

using System; using System.Windows.Forms; using System.Drawing; namespace Console_InputBox { class Tmp { static void Main(string[] args) {

string value = "Document 1"; //Tmp is class having static method InputBox if (Tmp.InputBox("New document", "New document name:", ref value) == DialogResult.OK) {

Console.WriteLine(value);
} Console.Read(); }

public static DialogResult InputBox(string title, string promptText, ref string value)
Form form = new Form(); Label label = new Label(); TextBox textBox = new TextBox(); //using class for creating runtime controls Button buttonOk = new Button(); Button buttonCancel = new Button(); form.Text = title; //title for form lable and default value for textbox label.Text = promptText; textBox.Text = value; buttonOk.Text = "OK"; //button text and dialog result: OK and Cancel {

buttonOk.DialogResult = DialogResult.OK; buttonCancel.DialogResult = DialogResult.Cancel;


label.SetBounds(9, 20, 372, 13); //bounds coord for controls textBox.SetBounds(12, 36, 372, 20);

buttonCancel.Text = "Cancel";

buttonOk.SetBounds(228, 72, 75, 23); buttonCancel.SetBounds(309, 72, 75, 23); label.AutoSize = true; //anchor docking bottom right textBox.Anchor = textBox.Anchor | AnchorStyles.Right; buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; form.ClientSize = new Size(396, 107); //form container adding controls and form A-C form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel }); form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.StartPosition = FormStartPosition.CenterScreen; form.MinimizeBox = false; form.MaximizeBox = false; form.AcceptButton = buttonOk; form.CancelButton = buttonCancel; //show dlg and value entered DialogResult dialogResult = form.ShowDialog(); value = textBox.Text; return dialogResult; } } }

To create custom dialog from add form follow the steps: Add form add two buttons OK and Cancel and text box and title DialogBox and label inside enter your name and;

in addition set formborderstyle property fixeddialog and controlbox property false; finally set the dialogresult property of button OK and Cancel button so that it returns result as OK and cancel dialog result; and now to display the form we use the showdialog method and not show since we need the dialogresult Ok and cancel clicked when ok clicked the text is given to main form; And then we need to create the Accept and CancelButton properties of form to buttons 1 and button 2

Main form: calling custom dialog

private void button5_Click(object sender, EventArgs e) { Form3 frm = new Form3(); if (frm.ShowDialog() == DialogResult.OK) textBox1.Text = frm.mytextbox.Text; }

- Some common operations on controls: Hiding displaying using visible property true/false and disabling and enabling with enabled property true/false; and can have focus for a control in form Activated event; you can specify the tab order for controls using the tabstop true and tabindex with index number; you can specify the access character for control for not only moue interaction but also character input; - Handling Common Key and Mouse events for forms and controls: Add labels textbox label and

button at bottom

private void textBox1_MouseEnter(object sender, EventArgs e) { textBox1.BackColor = Color.Red; textBox1.ForeColor = Color.White; } private void textBox1_MouseLeave(object sender, EventArgs e) { textBox1.BackColor = Color.White; textBox1.ForeColor = Color.Black; } private void textBox2_MouseEnter(object sender, EventArgs e) { textBox2.BackColor = Color.Red; textBox2.ForeColor = Color.White; }

private void textBox2_MouseLeave(object sender, EventArgs e) { textBox2.BackColor = Color.White; textBox2.ForeColor = Color.Black; } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("The total is " + (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text))); } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { label4.Text = "Enter only numbers."; textBox1.Text = ""; e.Handled = true; //event does not allow entry not nos } else { label4.Text=""; } } private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar)) { label4.Text = "Enter only numbers."; textBox2.Text = ""; e.Handled = true; //event does not allow entry not nos } else { label4.Text=""; }

Inheritance Picker:-

Visual Studio .NET allow you to add Items to Windows Project that we create. The following is the way to go for inheritance picker. Select project -> right click -> add-> add inherited form. Here you are show the inheritance picker where from you can choose the super class of you new form to be. Its like master page features you can inherit and cant change that but you can add your content

Basic Controls and their common events


1. Label: Used to display some text on the form. Instance of System.Windows.Forms.Label. Important properties are Text, Name and Font. 2. Button: Used to display a Push Button on the form. Instance of System.Windows.Forms.Button. Important

properties are Text, Name and Font. Usually the Click event is handled for the Button. 3. TextBox: Provides the user with an area to write/edit text. Instance of System.Windows.Forms.TextBox. Important properties are Text (to set startup text and get what the user has entered), Name, Alignment, Multiline (boolean), ScrollBars (a set of scroll bars attached with the text box), ReadOnly (boolean), WordWrap (boolean) and PasswordChar (character used for password masking). Important events are TextChanged (default) and KeyPress 4. GroupBox: Used to group other controls. Instance of System.Windows.Forms.GroupBox. Important properties are Text, Visible (boolean) and Enabled (boolean). Usually events are not handled for the GroupBox. 5. RadioButton : Allows a user to select one out of many available options. RadioButtons are usually used in a group contained in a GroupBox. Only one of the RadioButton can be selected in a group at a time. Instance of System.Windows.Forms.RadioButton. Important properties are Text, Name and Checked (boolean). Important event is CheckedChanged.

Usually the events of a RadioButton are not handled; rather the selected choice is identified on the click of some push button or actions on other controls. 6. CheckBox:Allows a user to tick or untick a box to state their preference for something. CheckBoxes are usually used in a group contained in a GroupBox. Any, all or none of the checkboxes in a group can be selected. Instance of System.Windows.Forms.CheckBox. Important properties are Text, Name, Checked (boolean) and CheckState. Important events are CheckedChanged and CheckStateChanged.

private void button1_Click(object sender, EventArgs e)

//purchase button click int sum = 0; string s = "Books Selected =>"; if (checkBox1.Checked) { sum += 100; //c# chkbox is s += checkBox1.Text + "\n"; } if (checkBox2.Checked) { sum += 200; s += checkBox2.Text + "\n"; } if (checkBox3.Checked) { sum += 250; s += checkBox3.Text + "\n"; }

selected;

if (radioButton1.Checked) s += "Payment Mode => " + radioButton1.Text; //if netbanking radio button is selected. else s += "Payment Mode => " + radioButton2.Text; s += "\nTotal Amount to be Payed => " + sum.ToString(); s += "\nProduct will be Delivered at Address:\n\n" + textBox1.Text; MessageBox.Show(s, "Payment"); } private void button2_Click(object sender, EventArgs e) { Application.Exit(); }

Adding items to the list box: A list box can be populated either at design time using the Visual Studio IDE or at runtime using code. We use following approach to add items to listbox programmatically lbxBooks.Items.Add("Programming C#"); lbxBooks.Items.Add("Professional C#"); Where lbxBooks is the instance of listbox added on the form Or if you want to add a series of items, you can use the

AddRange() method of the Items collection

private void Form1_Load(object sender, EventArgs e) { listBox1.Items.AddRange(new String[] {"Beginning C# by Wrox", "Professional C# by Wrox", "Programming C# by O' Reilly","Professional ASP.Net", "Beginning Java 2 by Wrox", "C++ - The complete Reference", "Java Servlets Programming", "Java Server Pages - JSP)"} ); }

Accessing items in the list box

- The Items collection of the list box provides the indexer property that allows items in the list box to be accessed programmatically (through the code). - Removing items from the list box: Individual items can be removed from the list box either by calling the Remove() or RemoveAt() method of the Items collection of the list box. The Remove() method accepts an object to be removed from the list box as lbxBooks.Items.Remove("Programming C#"); - The above line will remove the item Programming C# from the list box. You can also use the RemoveAt() method which accepts the index of the item to be removed from the list This line will remove the element at index 0 (the first element) from the list box. Finally, to remove all the

items contained in a list box, you can call the Clear() method.
private void button3_Click(object sender, EventArgs e) // changing list box item listBox1.Items[0] = "Program Development in Java"; string book1 = (string)listBox1.Items[1]; MessageBox.Show(book1 + " Now removing element and clear"); // reading list box item listBox1.Items.Remove(0);//index or specific text listBox1.Items.Clear(); } {

- Retrieving the Selected Value in ListBox: To programmatically retrieve, the item selected by the user at runtime, we use SelectedIndex or SelectedItem property of Listbox instance lbxBooks.SelectedIndex set/get the index of the selected item lbxBooks.SelectedItem set/get the selected Item value

MessageBox.Show(listBox1.SelectedIndex. ToString() + listBox1.SelectedItem.ToString());

We can use SelectedItems property, if user has selected multiple Items at runtime at any given point of time. listBox1.SelectedItems Get all the selected Items as collection To enable users to select more than one item, we should set SelectionMode property of listbox instance to Multiple, where as default value is Single. ListBox Event: SelectedIndexChanged is the event we commonly handle for listbox, and this will be triggered, whenever selection is changed private void lbxBooks_SelectedIndexChanged(object sender, System.EventArgs e) { MessageBox.Show("The selected item is " +

lbxBooks.SelectedItem.ToString(), "Selected Item"); }

The Menu as a whole is represented by MainMenu control, which in turn can have collection of menu items which can be represented by MenuItem class.Example Demonstrate usage of Menu control

class MenuForm { private void menuItemExit_Click(object sender, System.EventArgs e) { this.Dispose(); } private void menuItemOpen_Click(object sender, System.EventArgs e) { System.Diagnostics.Process.Start("c:\\winnt\\note pad.exe"); } }

Status bar It is a horizontal window of kind, visible at the bottom of the window it is associated with on which various kinds of status information n can be displayed. Example Demonstrate the Status bar and its usage. Step-1: Create a Windows Application Step-2: Drag the status bar from the tool bar and drop it on Form in the design mode

Step-3: Type out the following code Opt for MouseEnter and type out statusBarObject.Text="Mouse Entered Form Area!!!"; Opt for MouseLeave and type out statusBarObject.Text="Mouse Exited Form Area!!!";

ColorDialog - Enables Color selection from the interactive dialog window FontDialog - Enables Font selection from the interactive dialog window OpenFileDialog - Provides dialog box enables opening the selected file.

Example ColorDialog , FontDialog and OpenFileDialog collectively demonstrated by ToolBar

private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (e.ClickedItem.ToString().Equals("ColorDialog")) { colorDialog1.ShowDialog(); this.BackColor = colorDialog1.Color; MessageBox.Show("Color"); } else if (e.ClickedItem.ToString().Equals("FontDialog")) { fontDialog1.ShowDialog(); label1.Font = fontDialog1.Font; MessageBox.Show("Font"); } else if (e.ClickedItem.ToString().Equals("OpenFileDialog ")) { //openFileDialog1.ShowDialog(); Stream streamObject; int intData=0; if (openFileDialog1.ShowDialog() == DialogResult.OK) { if ((streamObject = openFileDialog1.OpenFile()) != null) { while ((intData = streamObject.ReadByte()) != -1) { richTextBox1.AppendText((char)intData + ""); } streamObject.Close(); } } MessageBox.Show("Open"); }

Regarding output The ColorDialog contribute to the change of Forms background color, FontDialog contributes to the change of Talent Transformation text , where as openFileDialog helps opening a selected file and read into richTextBox control

Assignment: Create a password dialog custom

implementation

ErrorProvider - It provides a simple mechanism for indicating the end user about an error associated with the control. In the case of any error it makes the icon flashes very next to the control which has error associated with. Error provider can also be made blinking, also we can as well set the Blink rate.

private void textBox1_Validating(object sender, CancelEventArgs e) { if (textBox1.Text == "") { errorProvider1.SetError(textBox1, "Enter your Name!!!"); textBox1.Focus(); } else { errorProvider1.Dispose(); } } private void textBox2_Validating(object sender, CancelEventArgs e) { if (textBox2.Text == "") { errorProvider1.SetError(textBox2, "Enter your MailID!!!"); textBox2.Focus(); } else { errorProvider1.Dispose(); } } private void textBox3_Validating(object sender, CancelEventArgs e) { if (textBox3.Text == "") { errorProvider1.SetError(textBox3, "Enter your MailID!!!"); textBox3.Focus(); } else { errorProvider1.Dispose(); }

You might also like