Write a Window application in C# that read employee recordfrom Microsoft access
ID: 3612100 • Letter: W
Question
Write a Window application in C# that read employee recordfrom Microsoft access database using odbc (Open DatabaseConnectivity). Your application would retrieve the employeerecords i.e. Employee id, name, address and age anddisplay this record using textbox control.Note:Don’tsend me the whole application. You just send me the codedisplaying how you connect with Microsoft access database and afterthat you read employee records from employee table. Employee id, name, address and age anddisplay this record using textbox control.
Note:Don’tsend me the whole application. You just send me the codedisplaying how you connect with Microsoft access database and afterthat you read employee records from employee table.
Explanation / Answer
// First table contains employees
// where empID is primary key, and foreign key
// emp (empID, name, address, age)
We have our database. Microsoft Access allows us to addrecords, but we want to create our own front end. To be able toconnect to the database and manipulate with records, it isnecessary to use the System.Data.OleDb namespace whichwill provide the required methods.
In the constructor of the initial form, the application connectsto the database using the following code
public Form1()
{
InitializeComponent();
// initiate DB connection
string connectionString ="Provider=Microsoft.Jet.OLEDB.4.0;
DataSource=empdb.mdb";
try
{
database = newOleDbConnection(connectionString);
database.Open();
//SQL query to listemployees
string queryString ="SELECT empID, name, address, age
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
The method loadDataGrid loads the data from the database to thedataGridView control, using the SQL query in the string variable,queryString. read/write data, using dataGridViewcontrol, adding buttons to cells, etc
public void loadDataGrid(string sqlQueryString) {
OleDbCommand SQLQuery = new OleDbCommand();
DataTable data = null;
dataGridView1.DataSource = null;
SQLQuery.Connection = null;
OleDbDataAdapter dataAdapter = null;
dataGridView1.Columns.Clear(); // <-- clear columns
SQLQuery.CommandText = sqlQueryString;
SQLQuery.Connection = database;
data = new DataTable();
dataAdapter = new OleDbDataAdapter(SQLQuery);
dataAdapter.Fill(data);
dataGridView1.DataSource = data;
dataGridView1.AllowUserToAddRows = false; // <-- remove the nullline
dataGridView1.ReadOnly = true; // <-- so the user cannottype
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.