Visual Programming 2018
Visual Programming 2018
Visual Programming
Using C#
-Work Sheets-
Prepared by:
Dareen Hamoudeh
Eman Al Naji
2018
Work Sheet 1
Hello World!
a. Font size: 16
b. Font Style: Bold
c. Font Color: Red
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).
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:
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:
Write code in the displayed buttons so that you create a simple calculator
Work Sheet 4
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.
Exercise:
Add a Button "Hide", in the form above, to hide the "Greetings GroupBox".
Work Sheet 5
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?
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
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
KeyEventArgs
Events Properties
Alt
Ctrl
Key Down Shift
Key Up Keycode
KeyData
KeyValue
KeyPressEventArgs
Events Properties
Key Press KeyChar
Work Sheet 9
Textbox3
Label5
Menus
Menustrip
Menuitem (Add, modify and delete)
Separater Line
Submenus
Shortcuts (Using &)
ShortCut property + ShowShortcut
Righttoleft property
Multiple Forms
1. Create the following form:
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.
In form3:
public partial class Form3 : Form
{
public Form3(string title)
{
InitializeComponent();
this.Text = title;
In form1:
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:
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:
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
Items
Text.
Dropdownstyle.
SelectedItem
SelectedIndex
Exercise:
Create the following form that contains a ComboBox to choose between two group
boxes:
Items
View
Columns
MultiSelect
LargeImageList
SmallImageList
SelectedItems
subItems
Count
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”.
Images.
Image size
TreeView
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
Example:
b. Update: used to change data that is already inserted into the table.
Syntax:
UPDATE table_name
[ WHERE CONDITION ];
Example:
UPDATE Students
WHERE StudentID = 1;
WHERE {CONDITION};
Example1: This statement deletes all records of students with majors "MIS"
- 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"
- 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.
- 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
- 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.
- 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();
finally
{
cn.Close();
}
}
finally // this means, that this command should be executed at the end,
either an exception was thrown or not.
{
cn.Close();
}
}
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();
finally
{
cn.Close();
}
}
if (textBox1.Text != "")
{
try
{
string sqlDelete = "DELETE FROM Students WHERE Student_Id = " +
textBox1.Text;
SqlCommand exeSqlDelete = new SqlCommand(sqlDelete, cn);
cn.Open();
exeSqlDelete.ExecuteNonQuery();
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();
finally
{
cn.Close();
}
}
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();
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;