Windows Forms - Winforms Controls
 

What are win form controls? How they are represented in .NET framework class library?

A form may contain various user interface (UI) controls. The controls represent the visual components that allow user to interact with the application and perform the desired task. All the controls, in .Net, are represented by subclasses of System.Windows.Forms.Control class. Each form has a collection (named ‘Controls’) to store the constituent controls of the form. In fact, a form itself is a special type of control called Container Control, i.e., the Form class itself is derived from the ContainerControl class which is a subclass of the Control class. A container control, as the name suggests, may contain other controls. Other examples of the Container control include Panel and Tab Control.

Each control, and thus form, exposes a number of events that can be triggered on certain user action or application behavior. For example, a button raises Click event whenever it is clicked and the text box raises the TextChanged event whenever its text is changed. The application developer can write even handler to catch these events and perform corresponding action. Beside these, a form also has certain set of events called the form life cycle events. These events are triggered during the life cycle of form to indicate the current state of the form.

What does it mean by docking of controls?

Docking is the property of the control to attach itself to a particular edge of the window (or other containing control). You can either dock a control to an edge or to fill the available space in the parent control or window. Common examples of docking includes menu bar and toolbars which dock themselves at the top of the window so that they may remain at top regardless of the size and of the window.

In the figure below, we have docked the button to the top of the window

When the control is resized, the control remains stuck to the top of the window

(Does it remind you the famous outlook bar?)

You can define a control to have a fill dock property so that it may fill all the available space in the parent window or parent control. In the figure below, we have docked the tree view control at left and the list view control with fill docking property

When the form is resized, the tree view will remain at left (changing only its height and not width) while the list view will expand itself to the rest of the available space on the form

(Does it remind you the famous Windows Explorer?)

A control is not docked to any edge, by default.


How do I set the tab order of the controls on the form?

To set the tab order of the controls on the form, select View -> Tab Order. This will start a wizard for setting the tab order. You can set the order of tab for the control by just clicking it in the same sequence as of required tab order.

What does it mean by anchoring of controls?

An anchoring is the property of the control to keep a specific distance with a particular edge of the window (or other containing control). You can anchor a control to any edge or side of the window, e.g., left, top, right, bottom, left and top, etc. If a control is anchored to the left of the window, it will keep the constant distance from the left side of the window; even when the window is resized. The constant distance that the control will keep with the window is the distance it has at the form startup or defined by its Location property. In the figure below, the button is anchored to the top edge of the window.

When the window is resized, it shifts itself on the form to keep the same distance from the top, see the figure below:

If we have defined the top and bottom anchoring and the form is resized, the control will resize itself to have the same distance from top and bottom. Consider the figure below; here the button is anchored top and bottom

When the form is resized, the button resizes itself to keep the same distance from top and bottom

The default anchoring of a control is left and top.

How do I set the anchoring property of my controls?

To change the anchoring property of the control, set the Anchor property of the control from the properties window. When you click the Anchor property of the control in the properties window, Visual Studio.NET will show you a tab to set the edges with which you wish to anchor the control

What are the fundamental and common properties of .NET controls?

Almost all the controls have some similar properties like Location, Size, Enabled, Visible, TabIndex, Name, Text, BacKColor, ForeColor, Font, etc. The TabIndex property is very important. It describes the sequence followed by the windows focus when the user presses the Tab button of keyboard


How do I set the docking property of my controls?

To change the docking property of the control, set the Dock property of the control from the properties window. When you click the Dock property of the control in the properties window, Visual Studio.NET will show you a tab to set the edges with which you wish to dock the control

How do I set the width of a ComboBox to fit the contents?

Move through the index items to find the longest item by character length using the MeasureString function. Use the this value as the ComboBox width.

System.Drawing.Graphics g = comboBox1.CreateGraphics();
 
float maxWidth = 0f; 
 
foreach(object o in comboBox1.Items) 
 
{  
float w = g.MeasureString(o.ToString(), comboBox1.Font).Width;
'checking the combobox for the longest text
if(w > maxWidth) 
maxWidth = w; 
'setting the width by checking the longest
text
} 
g.Dispose(); 
comboBox1.Width = (int) maxWidth
How do I browse and read a text file into a TextBox?

You use the OpenFileDialog to implement this functionailty.

 
using System.Text; 
using System.IO; 
private void button1_Click(object sender,
System.EventArgs e)
{ 
  OpenFileDialog ofd = new
OpenFileDialog();
  ofd.Title = "Open the
text file you wish" ;
  ofd.InitialDirectory =
"c:\" ;
  ofd.Filter = "txt files
(*.txt)|*.txt|All files (*.*)|*.*" ;
 
 if(ofd.ShowDialog() ==
DialogResult.OK)
   { 
    StreamReader sr
= File.OpenText(ofd.FileName);
    string s = sr.ReadLine();
    StringBuilder sb
= new StringBuilder();
    while (s != null)
      { 
       sb.Append(s);
       s
= sr.ReadLine();
      } 
      sr.Close();
      textBox1.Text
= sb.ToString();
   } 
}

How do I set the color and font in a RichEditBox?

Use the SelectionFont and SelectionColor properties to set the font and color of a RichEditBox. The following code will set the "selected text" to a blue-italic-verdana font set.

Note. If no text is selected then any all new text will be blue-italic-verdana within the RichEditBox.

 
RichTextBox1.Focus(); 
 
RichTextBox1.SelectionColor = Color.Blue;
 
RichTextBox1.SelectionFont = new Font ("Verdana",
12, FontStyle.Italic);


How to use the Splitter control?

The Splitter control is used to resize other controls. The purpose of this is to save space on the form.

This control can be very useful when you are working with controls both at design time and run time (which are not visible at design time).

How do I place restriction when entering some text in a textbox?

You can restrict a user from entering text against a set pattern. Or you can request the user only to enters certain type of

characters. E.g. Only a single digit number or a double digit number and so on. To control the input, use the KeyPress event like below:

Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As _ System.Windows.Forms.KeyPressEventArgs) Handles 

TextBox1.KeyPress

If(e.KeyChar < "10" Or e.KeyChar > "100") Then

MessageBox.Show("Enter Double Digits")

End If

End Sub

How do I access controls on another Form?

To access controls on other WinForms follow the example. This example reads the text in a textbox from other form and displays it in the textbox on the current form.

Open two forms (form1 and form2), add a Command Button and a Textbox to Form1 and a Textbox to Form2.

The following code relates to form1. 

Public Class Form1Inherits System.Windows.Forms.Form
Dim NewWindow As New Form2()

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

NewWindow.Show()

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

TextBox1.Text = NewWindow.TextBox1.Text

End Sub

End Class

When you run the code, Both

How can I access a Website/Webpage with a VB.NET LinkLabel control?

To access a Website or a Webpage using a VB.NET application. Drag a LinkLabel control and write the following code in it’s click event.

Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As 

System.Windows.Forms.LinkLabelLinkClickedEventArgs)Handles_

LinkLabel1.LinkClicked

System.Diagnostics.Process.Start("www.yahoo.com")

End Sub

Upon running the application,click on the Text on the LinkLabel. The website, Yahoo.com will open in a new browser.

How do I add items to a ComboBox and sort them?

The following code shows how to add items to a ComboBox.

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

ComboBox1.Items.Add(“India”)

ComboBox1.Items.Add(“Australia”)

ComboBox1.Items.Add(“Sweden”)

ComboBox1.Items.Add(“Spain”)

ComboBox1.Items.Add(“England”)

ComboBox1.Items.Add(“United States”)

ComboBox1.Items.Add(“Russia”)

ComboBox1.Items.Add(“China”)

ComboBox1.Items.Add(“Japan”)

ComboBox1.Items.Add(“New Zeland”)

End Sub

To sort the items alpahbetically, select the .Sorted property and set it to True.

How do I load a picture into the PictureBox control?

To load a Picture into the PictureBox control drag a PictureBox control and a Command Button from the Toolbox. When you click the Command Button, the picture you specified will be loaded into the Picturebox.

The following code is a demonstration.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PictureBox1.Image=Image.FromFile("C:\images\image.gif")
'Assuming you have a folder named images in C: drive and a gif image in that
End Sub

How do I add a control to windows form at runtime?

To add a control to a Form at Runtime, firstly decide which control is needed. Set all relevent properties and finally use the Controls.Add(controlname) function.

An an example of how to add a TextBox:

Dim tb as TextBox = New TextBox() 
'declaring a textbox 
tb.Size = New Size(130, 25) 
'setting the size for the textbox
tb.Location = New Point( 50, 70) 
'setting the location 
tb.Text = "Textbox1" 
'setting the text
Me.Controls.Add(tb)
dding the textbox to the form

How to create an "Explorer style" application in VB.NET?

Displaying all the drives, folders and files in an application like "Explorer" can be done easily in VB.NET. To do this follow these simple instructions:

Open a new project Add a Command Button to the Form. Place the following code in the click event of the command button.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click
Dim expl As New ExplorerStyleViewer()
expl.Show()
End Sub

What is a Tooltip control and how should I use it?

A Tooltip is a tag that displays some text when an ojects Mouse Over event is triggered. This is usually a decription of the object or the action that will follow if the object is say for example clicked.

Assume that there is a TextBox on a Form and we want to display a description when the mouse is over the TextBox.

Below is an example:

Private Sub Form5_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load
ToolTip1.SetToolTip(TextBox1, "Enter Some text")
'using the SetToolTip method to set the tip for the TextBox and the text that should appear
End Sub


XML How do you test if an attribute exists in the xml document?

String Value="";

if (Node.Attributes["Attribute1"] == null)

{

// doesn't exist

Value="";

}

else

{

// exists

Value=Node.Attributes["Attribute1"].Value.ToString();

}