0% found this document useful (0 votes)
10 views62 pages

Visual Programming 2018

This document contains a series of worksheets for a Visual Programming course using C#. It includes exercises on creating forms, manipulating controls like buttons, labels, textboxes, and checkboxes, as well as database concepts and SQL. Each worksheet provides step-by-step instructions for various programming tasks and concepts related to C# and Windows Forms development.

Uploaded by

Ahmed Al-nasheri
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)
10 views62 pages

Visual Programming 2018

This document contains a series of worksheets for a Visual Programming course using C#. It includes exercises on creating forms, manipulating controls like buttons, labels, textboxes, and checkboxes, as well as database concepts and SQL. Each worksheet provides step-by-step instructions for various programming tasks and concepts related to C# and Windows Forms development.

Uploaded by

Ahmed Al-nasheri
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/ 62

Philadelphia University

Faculty of Information Technology

Visual Programming
Using C#
-Work Sheets-

Prepared by:
Dareen Hamoudeh
Eman Al Naji
2018
Work Sheet 1

Hello World!

1. Create a New Project, Name it “Welcome”.

2. Add a PictureBox and a Label.

3. Change the Title of the form to “Hello”

4. Change the “Text” of the Label to “Hello World!”.

5. Change the font of the label as following:

a. Font size: 16
b. Font Style: Bold
c. Font Color: Red

6. Import a picture into the PictureBox.

7. Run the Form.


Work Sheet 2

Form, Buttons and labels Properties

Changing properties through properties window:

1. Change the following Form properties:


a) Change the form title to “worksheet1” (text).
b) Set the Background color to blue (BackColor).
c) Set the font color to red (ForeColor).
d) Change e font style (Font)
e) Set the form size to 300 x 300 (Size).
f) Specify the Maximum form Size to be 500 x 500 (MaximumSize).
g) Specify the Minimum form Size to be 100 x 100 (MinimumSize).

2. Place three Buttons on the form, and change their properties as follows:
a) Change buttons titles to “Ok, Exit, Disable “(text).
b) Change buttons names to “Ok, Ex, Dis “(Name).
c) Set the buttons size to 50 x 50 (size).
d) Set the location for the ok button to be 60,60. And the Exit button to be
150,60.
e) Disable any button and notice the change (Enable).
f) Set the visible property to be false for any button and notice the change
(visible).

3. Drag a label on the form:


a. Write the following text on it:” welcome to project 1”.
b. Change the Autosize property to false.
c. Change font style, color and alignment.
Changing properties at run time:

Write the appropriate code to apply the following:

a) Insert a button that changes the Form’s background color.


b) Insert a button that hides\shows the label.
c) Disable button will disable the “Hide” button.
d) The Ok button shows a welcome message.
e) Exit button closes the form.
Work Sheet 3

Textboxes Properties and Exercises

Changing properties through properties window:

4. Drag a Textbox to the current form, and change the following Form
properties:
h) Enable your textbox to contain several lines (Multiline)
i) Show scrollbars in the textbox (ScrollBars).
j) Enable your textbox to create a new line whenever you reach the border.
(WordWrap).
k) Add a default value to your textbox (Text).
l) Change the font color in the textbox (forecolor)
m) Forbid user to write in the textbox (Readonly)
n) Forbid user access to the textbox (Enabled)
o) Use your textbox for entering a password (PasswordChar)
p) Use your textbox for entering a password, using the system symbol
(UseSystemPasswordChar).
q) Add other 3 textboxes.
r) Change the TabIndex property for each textbox, so that the navigation
between them will change.
Exercise 1:

Create the following form:

Add code that does the following:

a) Change Title: Changes the title of the form according to the text entered in
the textbox (title).
b) Show/Hide: Shows and hides the label, the textbox and the button of the
Title.
c) Join: Joins the first name and last name inserted in the textboxes, and stores
the results in Full Name.
a. Use + operator
b. Use AppendText Method.
d) Go to Title: transfers the focus to Title Textbox
e) Repeat the code written in Join button, so that it occurs in "Textchanged"
event.
Exercise 2:

Create the following form:

Write code in the displayed buttons so that you create a simple calculator
Work Sheet 4

Group boxes and panels

Group boxes and panels: are used to group and contain controls, when moving
them all controls (inside them) moves.
Create the following form that contains a group box and a panel.

Notice the differences between them through the following properties:

Group box Caption No Same border


Scrollbar

panel No caption Scrollbars Change border

Exercise:

Add a Button "Hide", in the form above, to hide the "Greetings GroupBox".
Work Sheet 5

Check boxes and Radio buttons

Create the following form:

1. Study the following properties for check boxes:


 Text.
 Checked.
 Check state.

2. Study the following properties for Radio buttons:


 Text.
 Checked.

3. write code to do the following:

1. Activate the 4 checkboxes in the form, so that whenever a checkbox is checked,


the corresponding property is applied, otherwise it becomes false.
2. Activate the 2 radio buttons, so that whenever the "Personal" is checked, the first
panel is shown, and the other is hidden, and whenever the "Education" is checked,
vice versa.

3. Add a button, "Reset", that changes the checkstate property of any chosen
checkbox to "indeterminate".

Exercise 1:

Create the following form, but first add the six radio buttons without the
groupboxes, and check their behavior.

Question: can you choose "Arial" with "Bold" at the same time?

- Now, add the group boxes and check the difference in the radio buttons
behavior.
- Activate the radio buttons so that they change the size, name and style of the
label font.

- Check the behavior of the "Style" radio buttons, can you select "Bold" and
"Italic" at the same time?

- Activate the checkboxes, and note the difference.


Work Sheet 6

Message box and picture box

Build the following form, where:

1. When the user clicks on the button, the following message box shows:

2. If the user clicks on the OK button, a label shows with “you clicked the Ok
button”.
3. If the user clicks on the Cancel button, a label shows with “you clicked the
Cancel button”.
4. Each time the user clicks on the picture box, the image changes.
Work Sheet 7

Mouse Events

Create the following form, where:

Label 2
Label 3

1. While the cursor moves over the image, the coordinates x and y for the
curser position appear on the form.
2. When the user clicks on the image, the coordinates x and y for the curser
position appear on the form.
3. When the cursor enters the text box, the font size increases, and when the
cursor leaves the text box, the font size returns to its default size.
4. The text in label 2 will be changed to up, down or hover according to the
event performed on the mouse.
5. The text in label 3 will be changed to ”left” if the user clicked on the left
mouse button , and to ”right” if the user clicked on the right mouse button.
Work Sheet 8

Keyboard Events

Work Sheet 7

Create the following form, where:

We will study the following Keyboard Events:

KeyEventArgs
Events Properties
Alt
Ctrl
Key Down Shift
Key Up Keycode
KeyData
KeyValue
KeyPressEventArgs
Events Properties
Key Press KeyChar
Work Sheet 9

NumericUpDown, ToolTip, and LinkLabel

Create the following form, where:

Textbox3

Label5

1. The value in the age textbox must be between 18 and 30 (numericupdown).


2. When the user chooses his age, the value will show in label5 too.
3. When the curser hovers over the age textbox, a note (using tooltip control)
shows as shown in the picture.
4. The user can write his age in textbox3, the value will be stored in the
numericupdown.
5. When the user clicks on Philadelphia link, the university website opens.
6. When the user clicks on calculator link, the calculator application opens.
7. When the user clicks on MS word link, the MS word application opens.
8. When the user clicks on Pictures link, the Pictures folder opens.
Work Sheet 10

Menus

First: Create the following form, with the displayed menu:

Discuss the following concepts:

 Menustrip
 Menuitem (Add, modify and delete)
 Separater Line
 Submenus
 Shortcuts (Using &)
 ShortCut property + ShowShortcut
 Righttoleft property

Second: Create another form, with the following Menu


Add an ordinary label to the form, then

Activate the displayed menu items as follows:

A) Close  Closes the form


B) Red  Changes the font color of the label into red
C) Blue  Changes the font color of the label into blue
D) Green  Changes the font color of the label into green
E) Times New Roman  Changes the font name of the label to "Times New
Roman"
F) Arial  Changes the font name of the label to "Arial"
G) Tahoma  Changes the font name of the label to "Tahoma"
H) Bold, Italic and Underline  each changes the style of the label font
Hint: Make them act like Checkboxes, working with properties
(CheckOnClick and Checked)
Work Sheet 11

Multiple Forms
1. Create the following form:

2. Now create form2:


To create another form on your project: Go to "Solution Explorer", right-click on your
project name, and select this option.
Click New item, and the following screen will appear:

Select "Windows Form", and you can change the form name if you like.
When you press add, a new form will be created, and opened in a designed tab, and
displayed in the Solution Explorer.

Now, only add a button in this new form

3. Add a third form, and add one button. "Cancel".


4. Return to Form1, and on button "Form2" call form2.

private void button1_Click(object sender, EventArgs e)


{
Form2 f2 = new Form2();
f2.Show();
}

5. Activate "Cancel" button on Form2, so that it closes the form.


6. Return to Form1, and on button "Form3" call form3, and change the title of it as the user
specifies in the textbox.

In form3:
public partial class Form3 : Form
{
public Form3(string title)
{
InitializeComponent();
this.Text = title;

In form1:

private void button2_Click(object sender, EventArgs e)


{
Form3 f3 = new Form3(textBox1.Text);
f3.Show();
}

7. Activate the cancel button in Form3, to close the form.


8. Activate the Close button in Form1, to close the form.

Notes:

1. You can call the same form several times, and opens it several times, because you are
actually creating an object several times.
2. When you close the main form (which called the other forms), all forms are closed.
Work Sheet 12

ListBoxes

First: Review listBox control item and its main properties, methods and
default event.

Create the following form, and add a Listbox with the following items in it:

- Review the property SelectionMode and change its value (One,


MultiSimple, MultiExtended)
- Change the property Sorted into True, and check the effect.
- Add two labels to the form.
- In the first label, display the selectedItem (use the default event
SelectedIndexChanged).
- In the second label, display the selectedIndex. (check its value when no
items are selected)
- Discuss the properties SelectedItems and SelectedIndecies.
- If a user selects either C++ or C#, display a message "Welcome to C
languages". (hint: use method GetSelected)
- Add a button labeled "Count" and another label. When pressing the
button, display number of items in the listbox in the new label.
Second: Practice several actions on the listBox.

Create the following form:

Activate the displayed buttons as follows:

1. Add: Adds the item entered in the textbox into the listbox.
2. Remove: Removes the selected item in the listbox (Ex: Change it to
remove the written item in the textbox).
3. Clear List: Clears/removes all items in the listbox
4. Clear Selected: Removes the selection on items in the listbox.
Exercise 5:

Create the following form:

Activate the displayed buttons, so that:

1. > : moves the selected item from left listbox to the right one.
2. <: moves the selected item from right listbox to the left one
3. >>: moves all items from left listbox to the right one.
4. <<: moves all items from right listbox to the left one.

Change the code in > and < buttons, so that they move the selected
items.
Work Sheet 13

Combo box

Create the following form, where:

Study the following properties:

 Items
 Text.
 Dropdownstyle.
 SelectedItem
 SelectedIndex

Exercise:
Create the following form that contains a ComboBox to choose between two group
boxes:

Add/Sub and Mul/Div as the following:


Work Sheet 14

List View, Image list


9. Create the following form:

Study the following properties:

 Items
 View
 Columns
 MultiSelect
 LargeImageList
 SmallImageList
 SelectedItems
 subItems
 Count

Study the following Methods:

 Items.Add()
 Subitems. Add()
 Items.Clear()
The following event (ItemSelectionChanged) is used to reach a selected item using the object
(e):
 e.Isselected
 e.item
 e.item.subitems

10. Add two Image Lists to the form, one for small images and name it “small” and the
other for large images and name it “large”.

For each imageList, study the following properties :

 Images.
 Image size

11. Connecting the list view with the image lists:


a) Now, for the list view, change the smallImageList property to small,
and largeImageList property to large.
b) For each item in the list view, change the image index.
Exercise:

Create the following form


Work Sheet 15

TreeView

Create the following form, and study the following:

Properties:

 Nodes
 Check Boxes
 Image List
 Selected Node
 Checked
 FirstNode \ LastNode
 Parent.
 FullPath
 NextNode \ prevNode
 Text
 Name
 Tag
Methods:
 Collapse()
 Expand()
 ExpandAll()
 GetNodeCount()
 Add()

Exercise:
Creating a Database in Visual Studio 2012

1. Basic Database Concepts:


a. A database: is a collection of related data, organized into entities called tables
that are connected together by relationships.
b. A Table: is a part of the database that contains related information about a certain
entity (Students, Teachers, Faculties, etc.).
A table consists of fields that represent the needed information. A certain data
type should be specified for each field (e.g. StudentName "string or varchar",
CreditHours "Int", etc.)
Field
c. Primary Key: A unique field, that shouldn't be repeated in any record, and
shouldn't be null.

StudentID StudentName Major


200010101 Ahmad CS
Record 200010102 Ali CIS
200010103 Mohammad MIS
200010104 Maha SE

2. SQL (Structured Query Language):


SQL: is a language used to manage databases.
SQL is divided into two parts:
a. DDL: Data Definition Language, which consists of statements used to create
tables, fields, constraints, and other database objects.
b. DML: Data Manipulation Language, which consists of statements that inserts,
updates and deletes data into/from tables.

3. Basic DML Statements:


a. Insert: used to insert records into table.
Syntax:

INSERT INTO table_name( column1, column2....columnN)

VALUES ( value1, value2....valueN);

Example:

INSERT INTO Students( StudentID, StudentName, Major)


VALUES (1, "Ahmad", "CS");

b. Update: used to change data that is already inserted into the table.
Syntax:

UPDATE table_name

SET column1 = value1, column2 = value2....columnN=valueN

[ WHERE CONDITION ];

Example:

UPDATE Students

SET Major = "MIS"

WHERE StudentID = 1;

c. Delete: Deletes records from table according to certain conditions:


Syntax:

DELETE FROM table_name

WHERE {CONDITION};

Example1: This statement deletes all records of students with majors "MIS"

DELETE FROM Students

WHERE Major = "MIS";

Example2: This statement deletes all records in table students.

DELETE FROM Students;


4. Creating a local database in Visual Studio 2012.
Note: This is a different way to create a local database, you can use it, or use the one
explained in slides of Chapter5
- Create a new project, for example "DatabaseTest". Change the size of the form as
desired.

- To create the database, Add item to your project


- From "Data" category, choose "Service-based Database", make sure the extension of
your database is ".mdf", then click "Add".

The name of the


created database
- Choose a database model, select "Dataset", then Next.

- Retrieving database information, but of course we are creating an empty database at the
beginning, so no information will be retrieved.
- Press Finish.
- Check the "Solution Explorer", you will find the created database, and dataset.
- Now go to window, "Server Explorer". If it is not already displayed on the screen, you can
get it from "View" menu.
- Notice that the database "Database1.mdf" is created, and below it, the objects that can be
created within this database are displayed. Check "Tables" you will find it empty since we
haven’t created any tables yet.
- To add a new table, right-click on tables, and select "Add New Table"

- The table design tab will appear

- Notice that a new table with name "Table" is created, with only one field called "Id" by
default, and considered the primary key.
- Of course you can change the name of this field, if you wish, and you can specify another
field as a primary key.
- Rename the "Id" field into "Student_Id", make sure that the Data type is still int, and check
the "Allow Nulls" is not checked because this is the primary key.

- You can add other fields into your table as follows.

- Suppose you want to specify another field as primary key, just right-click on it and choose
"Set Primary Key".
- If you want to remove the primary key from "Student_Id", also you should rignt-click it, and
choose "Remove Primary Key"

- Of course, you can delete any field by clicking the "Delete" option.
- Now, check the below section from the screen, you can find a script of code that is used to
create the table you designed above.

- From this section, you can change the name of your table, to "Students" for example.

- To save this table into your database, don't use the regular "Save" or "Save as"
commands/buttons, since they will only create a script file with the code.
- To save your table into your database, press "Update"
- The following dialogue will be displayed

- Press "Update Database"


- In the "Data Tools Operations" window, messages will be displayed indicating that the
database is updated, by creating the new table.
- To make sure that your table has been created, go to the "Server Explorer" window, and press
"Refresh" to show the table.

- Then you can view your table, with all the fields created in it.
- Now, the table is created, but you need to add new data in it. You will have to design your
form, to display the data, and enable the user to manipulate (insert, update and delete) it.
- Add labels and textboxes and a button to your form as follows.

- Now, we need a control that is used to display the data in the table, we use "DataGridView",
from "Data" category in the "ToolBox".
- Add it to your form, as follows.
- Go to the small arrow, at the top of the datagridview, and go to "Choose data source", but
when you open it, you won’t be able to display the new database at the beginning.
- To refresh your database, and retrieve the needed table, go to section "Data Source" , if it is
not displayed on your screen, you can get it from "View" menu.
- The Data Source window will appear as following.

- Press the highlighted button to configure your dataset.

- Which will display the following wizard:


- Check on Table "Students", which will automatically check all the fields in this table, and
press "Finish"
- Now, return back to the "Data Source" window, and you will find your table with all its fields
there.

- Return back to the datagridview, and choose Data Source, and click on the required table.
En

- The DataGridView will look as the following, after you have bind it with table "Students".

- You can change the size (width) of each field, by changing this property from the property
window for each column (field).
- This property sheet will be displayed, so that you can change the properties of the selected
columns.

- Select "StudentName" and go to its property sheet, choose width, and change it in to 200.
- Now, to activate the button "Add New Record", double-click to open the default event-
handler.
- When you first view the code file, you will notice that an event-handler Form_Load, is
automatically generated with the following code.
- This method "Fill", should fill the DataGridView, with the data already inserted into this
table, i.e. it refreshes the data.
- Before starting coding the button, don't forget to define the following libraries (namespaces)
that should be used in your code.

- Return to button1_Click method, and start your code, by defining the connection string,
which will describe how your project will be connected to the database.

- Note: You can also get the connection string from the properties of the database file,
from “Data Source” window, and send it to the SqlConnection constructor as a
parameter.

- The next step, you should define the SQL statement that you want to execute, which should
be INSERT in this case. The statement is built as a string. In this statement you need to write
down the table name, and the fields' names in correct spelling, so that no errors will be
generated, copy the names from the properties of each of these objects.
- Of course, you need to fill values in this INSERT statement, so you will use the values
inserted by the user in the TextBoxes.
- After you define the string, you need to send it to an sqlCommand, that should be executed to
apply the insert, as follows.
- The next step, is to open the connection using method:
cn.open();
Then execute the command using method:
exeSqlInsert.ExecuteNonQuery();

- You can display a message to indicate to the user that your process is done successfully.

- You can use the same "Fill" method used in Form_Load method, to refresh the
DataGridView.

this.studentsTableAdapter.Fill(this.database1DataSet.Students);

- Now, run your project, fill the textboxes with data, and press the button.
- When OK button is pressed in the message, a new record will be added to the table.

- Try to add another record, with the Student Name written in Arabic Language, the
result will be as follows:
- The visual studio will not identify the Arabic language in the DataGridView, to force
it to identify it, write the letter 'N' before the field that you want the database to accept
Arabic letters in it, in the INSERT statement.
string sqlInsert = "INSERT INTO Students (Student_Id, StudentName, Major) values
("+textBox1.Text+", N'"+textBox2.Text+"', '"+textBox3.Text+"')";

- Finally, don't forget to close the connection when you finish by using
cn.Close();

- Now, suppose the user has entered wrong values into the table. For example, the
student id is kept null, or the user duplicates the user id. Then the insert process will
throw an exception (generate a runtime error). To avoid such an error, add the (try
and catch) block as the following.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new
SqlConnection(global::DatabaseTest.Properties.Settings.Default.Database1ConnectionString)
;
try
{
string sqlInsert = "INSERT INTO Students (Student_Id, StudentName, Major)
values (" + textBox1.Text + ", N'" + textBox2.Text + "', '" + textBox3.Text + "')";
SqlCommand exeSqlInsert = new SqlCommand(sqlInsert, cn);
cn.Open();
exeSqlInsert.ExecuteNonQuery();

MessageBox.Show("Add new record successfully!", "Message",


MessageBoxButtons.OK, MessageBoxIcon.Information);
this.studentsTableAdapter.Fill(this.database1DataSet.Students);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK,
MessageBoxIcon.Error);

finally
{
cn.Close();
}
}

- Add the following buttons to the form:


The entire code will be as the following:

private void Form1_Load(object sender, EventArgs e)


{
// TODO: This line of code loads data into the 'database1DataSet.Students'
table. You can move, or remove it, as needed.
this.studentsTableAdapter.Fill(this.database1DataSet.Students);

private void button1_Click(object sender, EventArgs e) // Add a new record


{
SqlConnection cn = new
SqlConnection(global::DatabaseTest.Properties.Settings.Default.Database1ConnectionString)
;
try
{
string sqlInsert = "INSERT INTO Students (Student_Id, StudentName, Major)
values (" + textBox1.Text + ", N'" + textBox2.Text + "', '" + textBox3.Text + "')";
SqlCommand exeSqlInsert = new SqlCommand(sqlInsert, cn);
cn.Open();
exeSqlInsert.ExecuteNonQuery();

MessageBox.Show("Add new record successfully!", "Message",


MessageBoxButtons.OK, MessageBoxIcon.Information);
this.studentsTableAdapter.Fill(this.database1DataSet.Students);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK,
MessageBoxIcon.Error);

finally // this means, that this command should be executed at the end,
either an exception was thrown or not.
{
cn.Close();
}
}

private void button2_Click(object sender, EventArgs e) // Update


{
SqlConnection cn = new
SqlConnection(global::DatabaseTest.Properties.Settings.Default.Database1ConnectionString)
;

try
{
string sqlUpdate = "UPDATE Students SET StudentName =
N'"+textBox2.Text+"', Major = '"+textBox3.Text+"' WHERE Student_Id = "+textBox1.Text;
SqlCommand exeSqlUpdate = new SqlCommand(sqlUpdate, cn);
cn.Open();
exeSqlUpdate.ExecuteNonQuery();

MessageBox.Show("Record updated successfully!", "Message",


MessageBoxButtons.OK, MessageBoxIcon.Information);
this.studentsTableAdapter.Fill(this.database1DataSet.Students);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK,
MessageBoxIcon.Error);

finally
{
cn.Close();
}
}

private void button3_Click(object sender, EventArgs e) //Delete


{
SqlConnection cn = new
SqlConnection(global::DatabaseTest.Properties.Settings.Default.Database1ConnectionString)
;

if (textBox1.Text != "")
{
try
{
string sqlDelete = "DELETE FROM Students WHERE Student_Id = " +
textBox1.Text;
SqlCommand exeSqlDelete = new SqlCommand(sqlDelete, cn);
cn.Open();
exeSqlDelete.ExecuteNonQuery();

MessageBox.Show("Record Deleted successfully!", "Message",


MessageBoxButtons.OK, MessageBoxIcon.Information);
this.studentsTableAdapter.Fill(this.database1DataSet.Students);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK,
MessageBoxIcon.Error);

finally
{
cn.Close();
}
}

else
MessageBox.Show("A Student id should be entered, to delete the student",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

}
private void button4_Click(object sender, EventArgs e) //Delete All
{
SqlConnection cn = new
SqlConnection(global::DatabaseTest.Properties.Settings.Default.Database1ConnectionString)
;
try
{
string sqlDelete = "DELETE FROM Students";
SqlCommand exeSqlDelete = new SqlCommand(sqlDelete, cn);
cn.Open();
exeSqlDelete.ExecuteNonQuery();

MessageBox.Show("All Records are deleted successfully!", "Message",


MessageBoxButtons.OK, MessageBoxIcon.Information);
this.studentsTableAdapter.Fill(this.database1DataSet.Students);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK,
MessageBoxIcon.Error);

finally
{
cn.Close();
}
}

private void button5_Click(object sender, EventArgs e)//Refresh


{
this.studentsTableAdapter.Fill(this.database1DataSet.Students);
}

Searching the data base:

Suppose you need to search the database for a certain data according to the user entry in a
textbox, and display the resulting data in the grid view, you have to do the following:

In this case, you will need to create a special datatable to store the data resulted from the given
query, and change the datasource of the datagridview, the following code will explain the steps:
private void button5_Click(object sender, EventArgs e) //search
{
try
{
con.Open();

string selectStat = "select * from stu where name = '" +


textBox4.Text+"'";
SqlCommand cmd = new SqlCommand(selectStat, con);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;

con.Close();

// disp_data();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
}

But, make sure to add the following statements in the other methods in your project (where you
need to display all data in the original table in the datagridview)
dataGridView1.DataSource = database1DataSet.Students;

You might also like