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


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 it’s the name given for GUI that constitutes part of microsoft . .net framework.

and position the form using startposition.Creating Windows Forms: when creating win forms create certain files form1.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.cs and designers code and program.cs and resources. ..


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


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

Forms.Form { ….Application------|-----Form Manages: run/exit | Controls Low level behavior class Form1 :System.Run(new frmObject()). [STAThread] static void Main() { Application. } .Windows. } ….

Windows.Forms.Drawing. using System.Forms and System. 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. namespace Console_InputBox { class Tmp { static void Main(string[] args) { . using System.Windows. and also custom code using runtime code for creating controls runtime for console application to support forms you have to add reference Sytem.Drawing using System.

36. //bounds coord for controls textBox. label. buttonCancel. TextBox textBox = new TextBox().DialogResult = DialogResult. string promptText. 372.WriteLine(value). } public static DialogResult InputBox(string title. ref string value) Form form = new Form().Read().Text = value.Text = title. //using class for creating runtime controls Button buttonOk = new Button(). 372.Text = "Cancel". //button text and dialog result: OK and Cancel { buttonOk. Label label = new Label(). 13). } Console.OK. //Tmp is class having static method InputBox if (Tmp.string value = "Document 1". Button buttonCancel = new Button(). //title for form lable and default value for textbox label. buttonCancel. "New document name:".Text = "OK". form. .DialogResult = DialogResult.OK) { Console.SetBounds(12. ref value) == DialogResult. 20.InputBox("New document".SetBounds(9.Text = promptText.Cancel. buttonOk. textBox. 20).

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

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. finally set the dialogresult property of button OK and Cancel button so that it returns result as OK and cancel dialog result.  And then we need to create the Accept and CancelButton properties of form to buttons 1 and button 2 Main form: calling custom dialog .in addition set formborderstyle property fixeddialog and controlbox property false.

Some common operations on controls: Hiding displaying using visible property true/false and disabling and enabling with enabled property true/false.Text = frm. you can specify the tab order for controls using the tabstop true and tabindex with index number.Text.ShowDialog() == DialogResult.OK) textBox1. } . 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 . .private void button5_Click(object sender. and can have focus for a control in form Activated event. EventArgs e) { Form3 frm = new Form3().mytextbox. if (frm.

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

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

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

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

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

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

EventArgs e) .private void button1_Click(object sender.

//c# chkbox is s += checkBox1.Text.Checked) s += "Payment Mode => " + radioButton1. if (checkBox1.Checked) { sum += 100.{ //purchase button click int sum = 0. if (radioButton1. EventArgs e) { Application.Checked) { sum += 200. } if (checkBox2. //if netbanking radio button is selected. else s += "Payment Mode => " + radioButton2.Text + "\n".Text. } private void button2_Click(object sender. s += checkBox2.Text. MessageBox. "Payment"). string s = "Books Selected =>".Text + "\n".Text + "\n".Checked) { sum += 250. s += "\nTotal Amount to be Payed => " + sum.Show(s.Exit(). } selected. s += "\nProduct will be Delivered at Address:\n\n" + textBox1. } if (checkBox3. } . s += checkBox3.ToString().


We use following approach to add items to listbox programmatically lbxBooks.Items. Where lbxBooks is the instance of listbox added on the form Or if you want to add a series of items.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. you can use the .Items.Add("Programming C#").Add("Professional C#"). lbxBooks.

"Professional ASP. "Java Server Pages . "Professional C# by Wrox".AddRange(new String[] {"Beginning C# by Wrox".Net".The complete Reference". EventArgs e) { listBox1. "Programming C# by O' Reilly". "Beginning Java 2 by Wrox".JSP)"} ).Items. } Accessing items in the list box .AddRange() method of the Items collection private void Form1_Load(object sender. "C++ . "Java Servlets Programming".

The above line will remove the item ’Programming C#’ from the list box. to remove all the . 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.Items. Finally. The Remove() method accepts an object to be removed from the list box as lbxBooks..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.Remove("Programming C#"). .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). .

Remove(0). // reading list box item listBox1.Retrieving the Selected Value in ListBox: To programmatically retrieve.Items[0] = "Program Development in Java".//index or specific text listBox1.Items[1].SelectedItem  set/get the selected Item value . } { .Clear(). private void button3_Click(object sender. string book1 = (string)listBox1. the item selected by the user at runtime.SelectedIndex  set/get the index of the selected item lbxBooks.Items.items contained in a list box. EventArgs e) // changing list box item listBox1. you can call the Clear() method.Items.Show(book1 + " Now removing element and clear"). MessageBox. we use SelectedIndex or SelectedItem property of Listbox instance lbxBooks.

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

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

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

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

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 . Example – Demonstrate the Status bar and its usage.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.

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

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

FontDialog and OpenFileDialog collectively demonstrated by ToolBar .Example – ColorDialog .

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

} Regarding output – The ColorDialog contribute to the change of Form’s background color. where as openFileDialog helps opening a selected file and read into richTextBox control Assignment: Create a password dialog custom . FontDialog contributes to the change of Talent Transformation text .

Error provider can also be made blinking.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. also we can as well set the Blink rate. .implementation - ErrorProvider .

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

} .

Sign up to vote on this title
UsefulNot useful