0% found this document useful (0 votes)
71 views

C# Task

The document discusses various properties and functionality of the TextBox, ComboBox, ListBox, RadioButton, and Button controls in C#. It provides code examples for setting properties like Text, BackColor, ForeColor, BorderStyle, MaxLength, DataSource, and DropDownStyle. It also demonstrates how to add/remove items from controls, retrieve selected values, refresh data sources, and handle events like SelectedIndexChanged.

Uploaded by

shabbirjamali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

C# Task

The document discusses various properties and functionality of the TextBox, ComboBox, ListBox, RadioButton, and Button controls in C#. It provides code examples for setting properties like Text, BackColor, ForeColor, BorderStyle, MaxLength, DataSource, and DropDownStyle. It also demonstrates how to add/remove items from controls, retrieve selected values, refresh data sources, and handle events like SelectedIndexChanged.

Uploaded by

shabbirjamali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

C# TextBox Control

A TextBox control is used to display, or accept as input, a single line


of text. This control has additional functionality that is not found in
the standard Windows text box control, including multiline editing
and password character masking.

or displaying a text in a TextBox control , you can code like this


textBox1.Text = "http://csharp.net-informations.com";

C# TextBox Properties

You can set TextBox properties through Property window or through


program. You can open Properties window by pressing F4 or right
click on a control and select Properties menu item

Background Color and Foreground Color

You can set background color and foreground color through property
window and programmatically.

textBox1.BackColor = Color.Blue;
textBox1.ForeColor = Color.White;
Textbox BorderStyle

You can set 3 different types of border style for textbox, they are
None, FixedSingle and fixed3d.

textBox1.BorderStyle = BorderStyle.Fixed3D;

Textbox Maximum Length

Sets the maximum number of characters or words the user can


input into the text box control.

textBox1.MaxLength = 40;

C# ComboBox Control
C# controls are located in the Toolbox of the development
environment, and you use them to create objects on a form with a
simple series of mouse clicks and dragging motions. A ComboBox
displays a text box combined with a ListBox, which enables the user
to select items from the list or enter a new value .
How add a item to combobox
comboBox1.Items.Add("Sunday");
comboBox1.Items.Add("Monday");
comboBox1.Items.Add("Tuesday");
ComboBox SelectedItem
How to retrieve value from ComboBox

If you want to retrieve the displayed item to a string variable , you


can code like this

string var;
var = comboBox1.Text;
Or
var item = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
MessageBox.Show(item);

How to remove an item from ComboBox

You can remove items from a combobox in two ways. You can
remove item at a the specified index or giving a specified item by
name.
comboBox1.Items.RemoveAt(1);

The above code will remove the second item from the combobox.
comboBox1.Items.Remove("Friday");

The above code will remove the item "Friday" from the combobox.

DropDownStyle

The DropDownStyle property specifies whether the list is always


displayed or whether the list is displayed in a drop-down. The
DropDownStyle property also specifies whether the text portion can
be edited.
comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
ComboBox Selected Value
How to set the selected item in a comboBox

You can display selected item in a combobox in two ways.

comboBox1.Items.Add("test1");
comboBox1.Items.Add("test2");
comboBox1.Items.Add("test3");
comboBox1.SelectedItem = "test3";
or
comboBox1.SelectedIndex = comboBox1.FindStringExact("test3");
ComboBox DataSource Property
How to populate a combo box with a DataSet ?

You can Programmatically Binding DataSource to ComboBox in a


simple way..

Consider an sql string like...."select au_id,au_lname from authors";

Make a datasource and bind it like the following...

comboBox1.DataSource = ds.Tables[0];
comboBox1.ValueMember = "au_id";
comboBox1.DisplayMember = "au_lname";
C# ListBox Control
The ListBox control enables you to display a list of items to the user
that the user can select by clicking.

How to bind a ListBox to a List ?

First you should create a fresh List Object and add items to the List.

List<string> nList = new List<string>();


nList.Add("January");
nList.Add("February");
nList.Add("March");
nList.Add("April");

The next step is to bind this List to the Listbox. In order to do that
you should set datasource of the Listbox.

listBox1.DataSource = nList;
Full Source code

private void button1_Click(object sender, EventArgs e)


{
List<string> nList = new List<string>();
nList.Add("January");
nList.Add("February");
nList.Add("March");
nList.Add("April");
listBox1.DataSource = nList;
}

How to bind a listbox to database values ?

First you should create a connection string and fetch data from
database to a Dataset.

connetionString = "Data Source=ServerName;Initial Catalog=databasename;User


ID=userid;Password=yourpassword";
sql = "select au_id,au_lname from authors";

After that you should set Listbox datasoure as Dataset.

listBox1.DataSource = ds.Tables[0];
listBox1.ValueMember = "au_id";
listBox1.DisplayMember = "au_lname";
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
//connetionString = "Data Source=ServerName;Initial
Catalog=databasename;User ID=userid;Password=yourpassword";
//sql = "select au_id,au_lname from authors";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
listBox1.DataSource = ds.Tables[0];
listBox1.ValueMember = "au_id";
listBox1.DisplayMember = "au_lname";
}
catch (Exception ex)
{
MessageBox.Show("Cannot open connection ! ");
}
}
}
}

How to refresh DataSource of a ListBox ?

How to clear the Listbox if its already binded with datasource


?

When you want to clear the Listbox, if the ListBox already binded
with Datasource, you have to set the Datasource of Listbox as null.

listBox1.DataSource = null;

How to SelectedIndexChanged event in ListBox ?

This event is fired when the item selection is changed in a ListBox.


You can use this event in a situation that you want select an item
from your listbox and accodring to this selection you can perform
other programming needs.

You can add the event handler using the Properties Window and
selecting the Event icon and double-clicking on
SelectedIndexChanged as you can see in following image.
The event will fire again when you select a new item. You can write
your code within SelectedIndexChanged event . When you double
click on ListBox the code will automatically come in you code editor
like the following image.

From the following example you can understand how to fire the
SelectedIndexChanged event

First you should drag two listboxes on your Form. First listbox you
should set the List as Datasource, the List contents follows:

List<string> nList = new List<string>();


nList.Add("First Quarter");
nList.Add("Second Quarter");

When you load this form you can see the listbox is populated with
List and displayed first quarter and second quarter. When you click
the "Fist Quarter" the next listbox is populated with first quarter
months and when you click "Second Quarter" you can see the
second listbox is changed to second quarter months. From the
following program you can understand how this happened.

C# RadioButton Control
A radio button or option button enables the user to select a single
option from a group of choices when paired with other RadioButton
controls. When a user clicks on a radio button, it becomes checked,
and all other radio buttons with same group become unchecked
The RadioButton control can display text, an Image, or both. Use
the Checked property to get or set the state of a RadioButton.
radioButton1.Checked = true;

The radio button and the check box are used for different functions.
Use a radio button when you want the user to choose only one
option. When you want the user to choose all appropriate options,
use a check box. Like check boxes, radio buttons support a Checked
property that indicates whether the radio button is selected.

RadioButton Properties
Checked:-
Gets or sets a value indicating whether the control is checked.

Examples
The following code example evaluates a ListBox selection and the Checked property of a RadioButton.
PerformClick method of
When a specified item is selected from the list box, the
another RadioButton is called. This example requires that two RadioButton controls and
a ListBox have been instantiated on a form.
private void ClickMyRadioButton()
{
// If Item1 is selected and radioButton2
// is checked, click radioButton1.
if (listBox1.Text == "Item1" && radioButton2.Checked)
{
radioButton1.PerformClick();
}
}
Property Value
Type: System.Drawing.Image

The Image displayed on the button control. The default value is null.

ButtonBase.Image Property
Image:

Gets or sets the image that is displayed on a button control.


Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)

Syntax
C#

C++

F#

VB
public Image Image { get; set; }
Property Value
Type: System.Drawing.Image

The Image displayed on the button control. The default value is null.

Remarks
When the Image property is set, the ImageList property will be set to null, and
the ImageIndex property will be set to its default, -1.

Note

If the FlatStyle property is set to FlatStyle.System, any images assigned to


the Image property are not displayed.
Examples
The following code example uses the derived class, Button and sets some of its common properties. The
result will be a flat button with text on the left and an image on the right. This code requires that you have
a bitmap image named MyBitMap.bmp stored in the C:\Graphics directory, and that a reference to
the System.Drawing namespace is included.

private void SetMyButtonProperties()


{
// Assign an image to the button.
button1.Image = Image.FromFile("C:\\Graphics\\MyBitmap.bmp");
// Align the image and text on the button.
button1.ImageAlign = ContentAlignment.MiddleRight;
button1.TextAlign = ContentAlignment.MiddleLeft;
// Give the button a flat appearance.
button1.FlatStyle = FlatStyle.Flat;
}

Control.Font Property
Font:-
Examples
The following code example displays a FontDialog to the user and changes the Font of
a DateTimePicker control. This example requires that you have a Form with Button and
a DateTimePicker on it.
private void myButton_Click(object sender, EventArgs e)
{
FontDialog myFontDialog = new FontDialog();
if(myFontDialog.ShowDialog() == DialogResult.OK)
{
// Set the control's font.
myDateTimePicker.Font = myFontDialog.Font;
}
}

LinkLabel Class
Represents a Windows label control that can display hyperlinks.
LinkBehavior Property
Gets or sets a value that represents the behavior of a link.

Examples
The following example demonstrates using the LinkLabel class, with multiple LinkArea sections
defined, to display a label on a form. The example demonstrates setting
the AutoSize, LinkBehavior, DisabledLinkColor, LinkColor, and VisitedLinkColor properties to
customize the look of the LinkLabel. The first LinkArea is specified using
the LinkLabel.LinkArea property. Additional links are added to the LinkLabel using
the LinkLabel.LinkCollection.Add method. The example handles the LinkClicked event by starting
the Web browser for hyperlinks, and displaying a MessageBox for other links.
using System;
using System.Drawing;
using System.Windows.Forms;

public class Form1 : System.Windows.Forms.Form


{
private System.Windows.Forms.LinkLabel linkLabel1;

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

public Form1()
{
// Create the LinkLabel.
this.linkLabel1 = new System.Windows.Forms.LinkLabel();

// Configure the LinkLabel's size and location. Specify that the


// size should be automatically determined by the content.
this.linkLabel1.Location = new System.Drawing.Point(34, 56);
this.linkLabel1.Size = new System.Drawing.Size(224, 16);
this.linkLabel1.AutoSize = true;

// Configure the appearance.


// Set the DisabledLinkColor so that a disabled link will show up
against the form's background.
this.linkLabel1.DisabledLinkColor = System.Drawing.Color.Red;
this.linkLabel1.VisitedLinkColor = System.Drawing.Color.Blue;
this.linkLabel1.LinkBehavior =
System.Windows.Forms.LinkBehavior.HoverUnderline;
this.linkLabel1.LinkColor = System.Drawing.Color.Navy;

this.linkLabel1.TabIndex = 0;
this.linkLabel1.TabStop = true;
// Add an event handler to do something when the links are clicked.
this.linkLabel1.LinkClicked += new
System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkCli
cked);

// Identify what the first Link is.


this.linkLabel1.LinkArea = new System.Windows.Forms.LinkArea(0, 8);

// Identify that the first link is visited already.


this.linkLabel1.Links[0].Visited = true;

// Set the Text property to a string.


this.linkLabel1.Text = "Register Online. Visit Microsoft. Visit
MSN.";

// Create new links using the Add method of the LinkCollection class.
// Underline the appropriate words in the LinkLabel's Text property.
// The words 'Register', 'Microsoft', and 'MSN' will
// all be underlined and behave as hyperlinks.

// First check that the Text property is long enough to accommodate


// the desired hyperlinked areas. If it's not, don't add hyperlinks.
if(this.linkLabel1.Text.Length >= 45)
{
this.linkLabel1.Links[0].LinkData = "Register";
this.linkLabel1.Links.Add(24, 9, "www.microsoft.com");
this.linkLabel1.Links.Add(42, 3, "www.msn.com");
// The second link is disabled and will appear as red.
this.linkLabel1.Links[1].Enabled = false;
}

// Set up how the form should be displayed and add the controls to
the form.
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.AddRange(new System.Windows.Forms.Control[]
{this.linkLabel1});
this.Text = "Link Label Example";
}

private void linkLabel1_LinkClicked(object sender,


System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
// Determine which link was clicked within the LinkLabel.
this.linkLabel1.Links[linkLabel1.Links.IndexOf(e.Link)].Visited =
true;

// Display the appropriate link based on the value of the


// LinkData property of the Link object.
string target = e.Link.LinkData as string;

// If the value looks like a URL, navigate to it.


// Otherwise, display it in a message box.
if(null != target && target.StartsWith("www"))
{
System.Diagnostics.Process.Start(target);
}
else
{
MessageBox.Show("Item clicked: " + target);
}
}
}

Anchor Property
Gets or sets the edges of the container to which a control is bound and determines how a control is
resized with its parent.

Examples
The following code example adds a Button to a form and sets some of its common properties. The
example anchors the button to the bottom-right corner of the form so it keeps its relative position as the
form is resized. Next it sets the BackgroundImage and resizes the button to the same size as
the Image. The example then sets the TabStop to true and sets the TabIndex property. Lastly, it adds
an event handler to handle the Click event of the button. This example requires that you have
an ImageList named imageList1.
// Add a button to a form and set some of its common properties.
private void AddMyButton()
{
// Create a button and add it to the form.
Button button1 = new Button();

// Anchor the button to the bottom right corner of the form


button1.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right);

// Assign a background image.


button1.BackgroundImage = imageList1.Images[0];

// Specify the layout style of the background image. Tile is the default.
button1.BackgroundImageLayout = ImageLayout.Center;

// Make the button the same size as the image.


button1.Size = button1.BackgroundImage.Size;

// Set the button's TabIndex and TabStop properties.


button1.TabIndex = 1;
button1.TabStop = true;

// Add a delegate to handle the Click event.


button1.Click += new System.EventHandler(this.button1_Click);

// Add the button to the form.


this.Controls.Add(button1);
}

AutoSize Property
Gets or sets a value indicating whether the control is automatically resized to display its entire
contents.

Examples
The following code example demonstrates the AutoSize property. To run this example, paste the following
code in a form and call the InitializeLabel method from the form's constructor or Load method
// Declare a label.
internal System.Windows.Forms.Label Label1;

// Initialize the label.


private void InitializeLabel()
{
this.Label1 = new Label();
this.Label1.Location = new System.Drawing.Point(10, 10);
this.Label1.Name = "Label1";
this.Label1.TabIndex = 0;

// Set the label to a small size, but set the AutoSize property
// to true. The label will adjust its length so all the text
// is visible, however if the label is wider than the form,
// the entire label will not be visible.
this.Label1.Size = new System.Drawing.Size(10, 10);
this.Controls.Add(this.Label1);
this.Label1.AutoSize = true;
this.Label1.Text = "The text in this label is longer" +
" than the set size.";

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy