Chapter 7- Windows Form and Database
Chapter 7- Windows Form and Database
Requirements
Exercises
3 REQUIREMENTS
1. Create database
Step 1: Server explorer
Step 2: Right Click on Data Connection
Step 3: Add Connection
Device Name
using System.Data.SqlClient;
string query= “SELECT * FROM Student”;
ConnectionString Gets or sets the string used to open a SQL Server database.
It is a path of database location.
string ConString= “Data Source=DESKTOP-254C50Q;Initial
Catalog=DB1;Integrated Security=True”
using System.Data.SqlClient;
string query= “SELECT * FROM Student”;
SqlDataReader reader = SqlDataReader class in C# is used to read data from the SQL Server database
cmd.ExecuteReader(); in the most efficient manner. It reads data in the forward-only direction.
It means once it reads a record, it will then read the next record; there is no
way to go back and read the previous record.
SqlDataAdapter adapter = new SqlDataAdapter in C# bridges a DataSet or DataTable and a Data Source
SqlDataAdapter(query, con); (SQL Server Database) to retrieve data.
-------------------------------------- It is a class that represents a set of SQL commands and a database
DataTable dt = new connection.
DataTable(); It is used to fill the DataSet or DataTable and update the data source as well.
adapter.Fill(dt); Fill(DataSet): a method in SqlDataAdapter class that used to add rows in the
DataSet to match those in the data source.
8 USEFUL COMMON CLASS AND METHODS
9 EXERCISES
STUDENT
#
Name StudID Gender
1
UJULU STUD001 Male
2
DIGNITY STUD002 Female
3
REDLINE STUD003 Male
10 EXERCISES
using System.Data.SqlClient;
static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-254C50Q;Initial
Catalog=SENG5z;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", con);
DataTable dt = new DataTable();
da.Fill(dt);
//********************************************
SqlCommand cmd= new SqlCommand("SELECT * FROM Student", con);
SqlDataReader reader = cmd.ExecuteReader();
//****************************************
}
11 EXERCISES
while (reader.Read())
{
Console.WriteLine(reader["Name"] + ", " + reader["StudID"] + ", " + reader["Gender"]);
}
12 EXERCISES
1. Create Database.
2. Create Table
3. Create the form
4. Insert Data into Table
5. Display Table data on DataGridView
6. Search By Name
13 CLASS WORK
TEACHING YOU IS GOOD LUCK