C - Sharp - Connecting - 2 - Insert, Update, and Delete Data From Local Database
C - Sharp - Connecting - 2 - Insert, Update, and Delete Data From Local Database
2.1 Update the Drugs table schema by adding more fields and more records
Now, explore the contents of the Drugs table and add the missing data. For example, the
expiry date field is empty since it is recently added to the table. To make the database
alteration operations more interesting add more records as shown in the following figure.
The group box is a container that holds any type of control as needed in
the application. From the group box properties change its Name
to gbDrugs, and change Text to “Drug Detail”. From the toolbox add a
Label, Text Box and DateTimePicker as shown in the figure.
The final arrangements of the controls on the form should be as shown in the following
figure:
2.3 Display the Selected Record from the
DataGridView
The if statement tests the database field (ExpiryDate), if the user leaves it blank or it is
retrieved from the database with a blank value then the date will not be displayed on
the dtpExpiryDate. Notice the use of Convert.ToDateTime to convert a string to date time.
Run the program now to ensure everything is working well. When a cell is clicked, the
corresponding record is displayed in the Drug Detail groupbox.
2.4 Update the DBConnection Class to Hold Insert, Update and Delete Functions
The DBConnection class is updated by including three functions. The first function
is drugInsert() that takes the drug info and inserts it into the database. The second function
is drugUpdate that takes the new info of the record and updates it. The third function
is drugDelete that takes the drug ID and deletes its record from the database. The following
code represents the functions inside the DBConnection Class.
The insertion in C# is done by creating a new ADO.Net object called SqlCeCommand. It holds
the SQL command that will be applied onto the database. The SqlCeCommand is initialized
by the SQL statement, the current connection, and the command type (Text or Stored
Procedure). The following function is added to the DBConnection class:
public int drugInsert(int ID,string Name,DateTime expDate,string company,string type)
{
try
{
string strCommand = "INSERT INTO Drugs(ID,Name,ExpiryDate,Company,Type)
VALUES(@ID,@Name,@ExpiryDate,@Company,@Type)";
SqlCeCommand cmdInsert = new SqlCeCommand();
cmdInsert.Connection = conn;
cmdInsert.CommandType = CommandType.Text;
cmdInsert.CommandText = strCommand;
cmdInsert.Parameters.AddWithValue("@ID", ID);
cmdInsert.Parameters.AddWithValue("@Name", Name);
cmdInsert.Parameters.AddWithValue("@ExpiryDate",expDate );
cmdInsert.Parameters.AddWithValue("@Company", company);
cmdInsert.Parameters.AddWithValue("@Type", type);
return cmdInsert.ExecuteNonQuery();
}
catch (SqlCeException e)
{
MessageBox.Show(e.Source + "\n" + e.Message + "\n" + e.StackTrace);
return -1;
}
}
The next step is to connect this command with the form. This can be done by opening
Form1 and double-clicking on the "Insert" button. The code editor will be opened for the
following code to be written, that is the Click procedure of the button
private void btnInsert_Click(object sender, EventArgs e)
{
if (txtID.Text.Length > 0 && txtName.Text.Length > 0)
{
int k = DBConn.drugInsert(Int32.Parse(txtID.Text), txtName.Text, dtpExpiryDate.Value.Date,
txtCompany.Text, txtType.Text);
if (k > 0)
{
dgvDrugs.DataSource = DBConn.getAllDrugs();
}
else
{
MessageBox.Show("No record inserted");
}
}
else
{
MessageBox.Show("Please fill in ID and Name of the drug");
}
}
The function checks the text in the ID TextBox and Name TextBox and ensures that the user
hasn't left them empty. The drugInsert method returns -1 if an error occurs together with a
message reporting the error, it returns 1 if a single record inserted. So the k value is always 1
for successful insertion of a single record.
The update of a record is done by using the same ADO.Net object “SqlCeCommand”. The
command is initialized by the command text, the current connection and command type.
The same procedure will be used as shown in the Insert function. Open the DBConnect class
and add the following code:
public int drugUpdate(string ID, string Name, DateTime expDate, string company, string type)
{
try
{
string strCommand = "Update Drugs Set Name=@Name, ExpiryDate=@ExpiryDate, Company=@Company,
Type=@Type WHERE ID=" + ID;
SqlCeCommand cmdUpdate = new SqlCeCommand();
cmdUpdate.Connection = conn;
cmdUpdate.CommandType = CommandType.Text;
cmdUpdate.CommandText = strCommand;
cmdUpdate.Parameters.AddWithValue("@ID", ID);
cmdUpdate.Parameters.AddWithValue("@Name", Name);
cmdUpdate.Parameters.AddWithValue("@ExpiryDate", expDate);
cmdUpdate.Parameters.AddWithValue("@Company", company);
cmdUpdate.Parameters.AddWithValue("@Type", type);
return cmdUpdate.ExecuteNonQuery();
}
catch (SqlCeException e)
{
MessageBox.Show(e.Source + "\n" + e.Message + "\n" + e.StackTrace);
return -1;
}
}
The preceding command is used in Form1 to update the current selected item from
the dgrDrugs. Open Form1 in design mode then double-click on the “Update” button, the
code editor will be opened for entering the following code:
private void btnUpdate_Click(object sender, EventArgs e)
{
string strID = dgvDrugs.CurrentRow.Cells["ID"].Value.ToString();
if (strID.Length > 0)
{
int k = DBConn.drugUpdate(txtID.Text, txtName.Text, dtpExpiryDate.Value.Date,
txtCompany.Text, txtType.Text);
if (k > 0)
{
dgvDrugs.DataSource = DBConn.getAllDrugs();
}
else
{
MessageBox.Show("No records updated");
}
}
else
MessageBox.Show("No record Selected");
}
The current selected row in the grid view is obtained. Then the ID field is checked for a valid
value, so "if ( strID.Length > 0)" is checking to ensure the user selected a row in the grid
view. The k value will be -1 for an error in the update or the numbr of records updated, it will
be greater than 0 (the count of the number of affected rows) when no errors are in the
update.
Run the program and make sure everything is working well. When the user clicks one of the
rows in the girdview, the corresponding data is displayed on the controls in the Drug Detail
group box. Try to change the contents of the controls and click the "Update" button. The
data will be updated and displayed directly into the GridView.
The record is deleted using only its ID. The car data can be deleted by passing the CarID to
the delete procedure, the procedure searches for that specific record and deletes it, if there
is more than one record with the same ID the procedure will delete them all. Add
the drugDelete function to the DBConnection class as follows: