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

C# Pratical

Uploaded by

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

C# Pratical

Uploaded by

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

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 Combo Box displays a text box combined with a List Box, which enables
the user to select items from the list or enter a new value

The user can type a value in the text field or click the button to display a drop down
list. You can add individual objects with the Add method. You can delete items with
the Remove method or clear the entire list with the Clear method

A ComboBox in C# is a graphical user interface (GUI) element that combines the features of a
text box and a drop-down list.

The following code stepwise illustrate the usage of ComboBox

private void Form1_Load(object sender, EventArgs e)


{
//First step

comboBox1.Items.Add("A");
comboBox1.Items.Add("B");
comboBox1.Items.Add("C");
//OR
this.comboBox1.Items.Add("A");
this.comboBox1.Items.Insert(0, "B");
this.comboBox1.Items.Insert(1, "C");
this.comboBox1.Items.Insert(2, "D");

//step no-5
this.comboBox2.Items.Add("Week");
this.comboBox2.Items.Add("Month");
}

private void button1_Click(object sender, EventArgs e)


{
//step no-3: this code will prevent empty space
if (this.textBox1.Text != "")
{
//Second step
// if TextBox is empty, then space will be added to ComboBox
after every click of Add button
this.comboBox1.Items.Add(this.textBox1.Text);
this.textBox1.Text = "";
this.textBox1.Focus();
}
}

private void removebtn_Click(object sender, EventArgs e)


{
// step no-4
this.comboBox1.Items.Clear();
// comboBox1.Items.Remove("A");

// this is used to remove selected items from ComboBox


// comboBox1.Items.Remove(comboBox1.SelectedItem);

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)


{
// step no-6: the following code will add days of the week or
months of the year if we select week from ComboBox2 days of the
week will be added automatically to ComboBox1 and so on.

comboBox1.Items.Clear();
if (this.comboBox2.SelectedItem == "Week")
// if (comboBox2.SelectedItem.Equals ("week") )

{
this.comboBox1.Items.Add("Sunday");
this.comboBox1.Items.Add("Monday");
this.comboBox1.Items.Add("Tuesday");
this.comboBox1.Items.Add("Wednesday");
this.comboBox1.Items.Add("Thursday");
this.comboBox1.Items.Add("Friday");
}
else if(comboBox2.SelectedItem =="Month")
// else if (comboBox2.SelectedItem.Equals ("Month") )

{
this.comboBox1.Items.Add ("January");
this.comboBox1.Items.Add ("February");
this.comboBox1.Items.Add ("March");
this.comboBox1.Items.Add ("April");
this.comboBox1.Items.Add ("May");
} }

-------------------------------------------------------------------------------------------------------------------------------

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

Add the following to above design

First step:

private void Form1_Load(object sender, EventArgs e)


{

this.redlbl.Visible = false;
bluelbl.Visible = false;
greenlbl.Visible = false;
}
Second step:

private void redrbtn_CheckedChanged(object sender, EventArgs e)


{

if (redrbtn.Checked == true)
{
redlbl.Visible = true;
bluelbl.Visible = false;
greenlbl.Visible = false;
}
}

Third step:

private void bluerbtn_CheckedChanged(object sender, EventArgs e)


{
if(bluerbtn.Checked == true )
{

bluelbl.Visible = true;
redlbl.Visible = false;
greenlbl.Visible = false;
}
}

Fourth step:

private void greenrbtn_CheckedChanged(object sender, EventArgs e)


{
if (greenrbtn.Checked ==true )
{
greenlbl.Visible = true;
redlbl.Visible = false;
bluelbl.Visible = false ;
}
}
ListBox Control

The ListBox control is the simplest of the list-based controls and serves primarily to display a
simple list of items in an easy-to-navigate user interface from which users can select one or
more items.

First step:

The following code stepwise illustrate above design

Second step: write the following code under form load event

private void Form1_Load(object sender, EventArgs e)


{
this.listBox1.Items.Add("Sunday");
this.listBox1.Items.Add("Monday");
this.listBox1.Items.Add("Tuesday");
this.listBox1.Items.Add("Wednesday");
this.listBox1.Items.Add("Thursday");
this.listBox1.Items.Add("Friday");

Step no-3:

private void addbtn_Click(object sender, EventArgs e)


{

// preventing List Box from duplicate data

string str = this.textBox1.Text;


bool duplicate = false;
foreach (object obj in listBox1.Items)
{
if (obj.ToString() == str)
{
duplicate = true;
break;
}
}
if (duplicate)
{
MessageBox.Show("name already exist");

}
else if (this.textBox1.Text != "")
{
this.listBox1.Items.Add(this.textBox1.Text);
this.textBox1.Clear();
this.textBox1.Focus();

}
Step no-4:

private void removebtn_Click(object sender, EventArgs e)


{
this.listBox1.Items.Remove(listBox1.SelectedItem);

Step no-5:

private void showbtn_Click(object sender, EventArgs e)


{
// This code is used to select multi index
listBox1.SelectionMode = SelectionMode.MultiSimple ;
//this code is used to display SelectedItems through message box
foreach (object obj in listBox1.SelectedItems)
{
MessageBox.Show(obj.ToString());
}
}
Step no-6:

private void loadlistbtn_Click(object sender, EventArgs e)


{
List<string> strlist = new List<string>();
strlist.Add("ali");
strlist.Add("raza");
strlist.Add("ajmal");

listBox1.DataSource = strlist;

//List<string> intlist = new List<string>();


//intlist.Insert(0, "Irfan");
//intlist.Insert(1, "Rashid");
//intlist.Insert(2, "Usman");
//listBox1.DataSource = intlist;

}
-------------------------------------------------------------------------------------------------------------------------------

Using Lable, TextBox and Button controls

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void showbtn_Click(object sender, EventArgs e)


{
//first
// if (this.firsttxt.Text != "")
if(this.firsttxt.Text.Length !=0)
{

// the above code is used for concatenation of string


// now we are going to add the values
int x = Convert.ToInt32(this.firsttxt.Text);
int y = int.Parse(this.secondtxt.Text);
this.resulttxt.Text = (x + y).ToString();
}
}

private void clearbtn_Click(object sender, EventArgs e)


{
//second
this.firsttxt.Text = "";
this.secondtxt.Text = "";
this.resulttxt.Text = "";

// OR
//firsttxt.Clear();
//secondtxt.Clear();
//resulttxt.Clear();
}

private void closebtn_Click(object sender, EventArgs e)


{
// Code for form closing
//this.Close();
// this.Dispose();
Application.Exit();

private void Form1_Load(object sender, EventArgs e)


{
// last step creating dynamic button

Button dynamicbtn = new Button();


dynamicbtn.Width = 90;
dynamicbtn.Height = 30;
dynamicbtn.Text = "Display";
dynamicbtn.Name = "button1";
dynamicbtn.BackColor = Color.Green;
dynamicbtn.ForeColor = Color.Red;
dynamicbtn.Location = new Point(100, 30);
dynamicbtn.Font = new Font("timenewroman", 12, FontStyle.Italic
);
Controls.Add(dynamicbtn);

//Assignment No-1: write down a program to create three buttons dynamically


at run time.

} } }

------------------------------------------------------------------------------------------------------------------------------------------

Adding additional forms to main form

The following figure illustrate the way of adding new form to the existing form

When we want to display the new Form from existing Form write the following code under click envent.

Form2 frm = new Form2();


frm.Show();
---------------------------------------------------------------------------------------------------------------------

Message Box

Write the following code under button click event. This code will reveals different aspects of Message
Box.

private void messagebtn_Click(object sender, EventArgs e)


{
// first step
//MessageBox.Show ("hello");

//second step
// MessageBox.Show("this is seventh semester","Semester",
MessageBoxButtons.YesNo);
// third step
if (MessageBox.Show("information", "semester",
MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
{
// Application.Exit();
this.Close();
}
if (Convert.ToBoolean(DialogResult.No ))
{
MessageBox.Show("please, try again");

-------------------------------------------------------------------------------------------------------------------------------

CheckedListBox Control

The CheckedListBox control gives you all the capability of a list box and
also allows you to display a check mark next to the items in the list box.
The user can place a check mark by one or more items and the checked items can
be navigated with the CheckedListBox.CheckedItemCollection and
CheckedListBox.CheckedIndexCollection.

A CheckedListBox in C# is a control that combines a list box with checkboxes,


allowing users to select multiple items by checking them.
First step:

Write the following code under form load event when CheckedListBox controls added to window
form.
this.checkedListBox1.Items.Add("Sunday");
this.checkedListBox1.Items.Add("Monday");
this.checkedListBox1.Items.Add("Tuesday");

Second step:

You can add individual items to the list with the Add method. The
CheckedListBox object supports three states through the CheckState
enumeration: Checked, Indeterminate, and Unchecked.

this.checkedListBox1.Items.Add("Sunday", CheckState.Checked );
this.checkedListBox1.Items.Add("Monday",CheckState.Indeterminate
);
this.checkedListBox1.Items.Add("Tuesday",CheckState.Unchecked );
---------------------------------------------------------------------------------------------

PictureBox Control

The Windows Forms PictureBox control is used to display images in


bitmap, GIF , icon , or JPEG formats.

You can set the Image property to the Image you want to display, either at design
time or at run time. You can programmatically change the image displayed in a
picture box, which is particularly useful when you use a single form to display
different pieces of information.

this.pictureBox1.Image = Image.FromFile("C:\\Users\\Airplane_img.jpg");

The SizeMode property, which is set to values in the PictureBoxSizeMode


enumeration, controls the clipping and positioning of the image in the display area.

pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
ProgressBar Control
A progress bar is a control that an application can use to indicate the
progress of a lengthy operation such as calculating a complex result,
downloading a large file from the Web etc.

ProgressBar controls are used whenever an operation takes more than a short
period of time. The Maximum and Minimum properties define the range of values to
represent the progress of a task.

Minimum : Sets the lower value.


Maximum : Sets the upper value.
Value : This property sets the current level of progress.

By default, Minimum and Maximum are set to 0 and 100. As the task proceeds, the
ProgressBar fills in from the left to the right. To delay the program briefly so that
you can view changes in the progress bar clearly.

The following code illustrate simple usage of progress bar.

private void button2_Click(object sender, EventArgs e)


{
this.progressBar1.Maximum = 200;
this.progressBar1.Minimum = 0;
for (int x = 0; x < 100; x++)
{

this.progressBar1.Value = x;

-------------------------------------------------------------------------------------
DateTimePicker Control

The DateTimePicker control allows you to display and collect date and time from the
user with a specified format. The DateTimePicker control has two parts, a label
that displays the selected date and a popup calendar that allows users to
select a new date. The most important property of the DateTimePicker is the Value
property, which holds the selected date and time.

The following code illustrate the above design which, is used to find out difference
between two selected date or time.

private void button1_Click(object sender, EventArgs e)


{
DateTime from = new DateTime();
DateTime to = new DateTime();
string diffrences;

from = dateTimePicker1.Value;
to = dateTimePicker2.Value;

diffrences = (to - from).TotalDays .ToString ();


this.textBox1.Text = diffrences;

}
Treeview Control
The TreeView control contains a hierarchy of TreeViewItem controls. It
provides a way to display information in a hierarchical structure by using
collapsible nodes . The top level in a tree view are root nodes that can be expanded
or collapsed if the nodes have child nodes.

You can explicitly define the TreeView content or a data source can provide the
content. The user can expand the TreeNode by clicking the plus sign (+) button.

Write the following code under form load event which reveals above design

private void Form1_Load(object sender, EventArgs e)


{

treeView1.Nodes.Add("Classes");
treeView1.Nodes[0].Nodes.Add("Fist Year");
treeView1.Nodes[0].Nodes[0].Nodes.Add("Early Morning");
treeView1.Nodes[0].Nodes[0].Nodes.Add("Late Morning");
treeView1.Nodes[0].Nodes[0].Nodes.Add("Evening");
treeView1.Nodes[0].Nodes.Add("Second Year");
treeView1.Nodes[0].Nodes[1].Nodes.Add("Early Morning");
treeView1.Nodes[0].Nodes[1].Nodes.Add("Late Morning");
treeView1.Nodes[0].Nodes[1].Nodes.Add("Evening");

------------------------------------------------------------------------------------
ListView Control

private void Form1_Load(object sender, EventArgs e)


{

listView1.GridLines = true;
// listView1.FullRowSelect = true;
// First Step:the following code shows adding columns to listview at run time

//this.listView1.View = View.Details;

//this.listView1.Columns.Add("ID", 100);
//this.listView1.Columns.Add("Name", 100);

//Second Step
//ListViewItem litem;
//litem =listView1.Items.Add("1");
//litem.SubItems.Add("asad");
//litem.SubItems.Add("SE");
//litem.SubItems.Add("A");
//litem = listView1.Items.Add("2");
//litem.SubItems.Add("ajmal");
//litem.SubItems.Add("SE");
//litem.SubItems.Add("B");

private void addbtn_Click(object sender, EventArgs e)


{
//Third Step

string[] str = new string[] { this.idtxt.Text, this.nametxt.Text,


this.depttxt.Text, this.gradetxt.Text };
ListViewItem litem = new ListViewItem(str);

listView1.Items.Add(litem);

}
private void listView1_Click(object sender, EventArgs e)
{
//Fourth Step

this.idtxt.Text = listView1.SelectedItems[0].SubItems[0].Text;
this.nametxt.Text = listView1.SelectedItems[0].SubItems[1].Text;
this.depttxt.Text = listView1.SelectedItems[0].SubItems[2].Text;
this.gradetxt.Text = listView1.SelectedItems[0].SubItems[3].Text;
}

private void deletebtn_Click(object sender, EventArgs e)


{

this.listView1.Items.Clear();

private void updatebtn_Click(object sender, EventArgs e)


{
listView1.SelectedItems[0].SubItems[0].Text = this.idtxt.Text;
listView1.SelectedItems[0].SubItems[1].Text = this.nametxt.Text;
listView1.SelectedItems[0].SubItems[2].Text = this.depttxt.Text;
listView1.SelectedItems[0].SubItems[3].Text = this.gradetxt.Text;

------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------

private void textBox1_KeyDown(object sender, KeyEventArgs e)


{
if (e.KeyCode == Keys.Enter )
{
this.textBox2.Focus();
}
}

private void textBox2_KeyDown(object sender, KeyEventArgs e)


{
if (e.KeyCode == Keys.Enter)
{
this.textBox3.Focus();
}
}

private void textBox3_KeyUp(object sender, KeyEventArgs e)


{

private void textBox3_KeyUp_1(object sender, KeyEventArgs e)


{
if (e.KeyCode == Keys.Up )
{
this.textBox2.Focus();
}
}

private void textBox2_KeyUp(object sender, KeyEventArgs e)


{
if (e.KeyCode == Keys.Up )
{
this.textBox1.Focus();
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication76
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
this.undoToolStripMenuItem.Enabled = false;
this.cutToolStripMenuItem.Enabled = false;
this.copyToolStripMenuItem.Enabled = false;
this.pasteToolStripMenuItem.Enabled = false;
this.deleteToolStripMenuItem.Enabled = false;
}

private void undoToolStripMenuItem_Click(object sender, EventArgs e)


{

this.richTextBox1.Undo();

private void richTextBox1_TextChanged(object sender, EventArgs e)


{
if(this.richTextBox1.Text !="")
{
this.undoToolStripMenuItem.Enabled = true;

}
}

private void cutToolStripMenuItem_Click(object sender, EventArgs e)


{
this.richTextBox1.Cut();
}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)


{
this.richTextBox1.Copy();
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)


{
this.richTextBox1.Paste();
}

private void deleteToolStripMenuItem_Click(object sender, EventArgs


e)
{
this.richTextBox1.Clear();
}

private void selectAllToolStripMenuItem_Click(object sender,


EventArgs e)
{
this.richTextBox1.SelectAll();
}

private void richTextBox1_SelectionChanged(object sender, EventArgs


e)
{
if(this.richTextBox1.SelectedText !="")
{
this.cutToolStripMenuItem.Enabled = true;
this.copyToolStripMenuItem.Enabled = true;
this.pasteToolStripMenuItem.Enabled = true;
this.deleteToolStripMenuItem.Enabled = true;

}
else
{

this.cutToolStripMenuItem.Enabled = false;
this.copyToolStripMenuItem.Enabled = false;
this.deleteToolStripMenuItem.Enabled = false;
}
}

private void newToolStripMenuItem_Click(object sender, EventArgs e)


{
this.richTextBox1.Text = "";
}

private void openToolStripMenuItem_Click(object sender, EventArgs e)


{
OpenFileDialog opdlg = new OpenFileDialog();
opdlg.Title = "Open";
opdlg.Filter = "Text Document|*.txt";
if(opdlg.ShowDialog ()== DialogResult.OK )
{
this.richTextBox1.LoadFile(opdlg.FileName,
RichTextBoxStreamType.PlainText);
this.Text = opdlg.FileName;

}
}

private void saveToolStripMenuItem_Click(object sender, EventArgs e)


{
SaveFileDialog sdlg = new SaveFileDialog();
sdlg.Title = "Save";
sdlg.Filter = "Text Document|*.txt";
sdlg.DefaultExt = ".txt";
if(sdlg.ShowDialog ()==DialogResult.OK )
{
this.richTextBox1.SaveFile(sdlg.FileName,
RichTextBoxStreamType.PlainText);
this.Text = sdlg.FileName;

}
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)


{
Application.Exit();
}

private void undoToolStripMenuItem1_Click(object sender, EventArgs e)


{
this.richTextBox1.Undo();
}

private void cutToolStripMenuItem1_Click(object sender, EventArgs e)


{
this.richTextBox1.Cut();
}

}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication86
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection();
public Form1()
{
con.ConnectionString = "data source=.; initial catalog=jahan; integrated
security=true";
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{

private void button4_Click(object sender, EventArgs e)


{
con.Open();
if(con.State == ConnectionState.Open )
{
MessageBox.Show("done");
}
}

private void button1_Click(object sender, EventArgs e)


{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into student(id,name,address)values(N'"
+ idtxt.Text
+ "',N'" + nametxt.Text + "',N'" + addresstxt.Text + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("data saved");
con.Close();
}

private void button2_Click(object sender, EventArgs e)


{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from student where id=N'" + idtxt.Text + "'";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("data deleted");
con.Close();
}

private void button3_Click(object sender, EventArgs e)


{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "update student set name='" + nametxt.Text
+ "', address='"
+ addresstxt.Text + "' where id='" + idtxt.Text + "'";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("data updated");
con.Close();
}

private void idtxt_TextChanged(object sender, EventArgs e)


{
SqlDataReader dr;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select *from student where id='" + idtxt.Text
+ "'";
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read ())
{
nametxt.Text = dr[@"name"].ToString();
addresstxt.Text = dr[@"address"].ToString();

}
con.Close();
}
}
}

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