I am trying to implement an Enum within a Save button (which inserts new records in a DB connected to the Visual Studio WinForms Application).
In this case, I have Books & Category Tables. Category is also a Foreign Key within Books table (as CategoryID, which should accept only int data type).
With that said, I would like the application to understand / convert a string value to an int value, for example:
If I input the value "History" within the Category Textbox in the application, and fill in the rest of the details required to insert a new book record in DB, and finally click Save Button, I need the application to understand that "History" would reflect an ID (in this case, ID: '4') in Category Table.
In short, I don't want to input int values in the application - I want to type in the Category Name in the CategoryID Textbox.
private void btnSave_Click(object sender, EventArgs e)
{
string ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=
C:\Program Files\Microsoft SQL
Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\Library System Project.mdf
;Integrated Security=True;Connect Timeout=30";
string Query = "insert into Books (BookName, BookAuthor, CategoryID, ClassificationID, BookAvailabilityQuantity, Price) values ('" + this.txtName.Text.Trim() + "','" + this.txtAuthor.Text.Trim() + "','" + this.txtCategory.Text.Trim() + "','" + this.txtClassification.Text.Trim() + "','" + this.txtAvailabilityQuantity.Text.Trim() + "','" + this.txtPrice.Text.Trim() + "');";
SqlConnection DBCon = new SqlConnection(ConnectionString);
SqlCommand DBCommand = new SqlCommand(Query, DBCon);
SqlDataReader DBReader;
try
{
DBCon.Open();
DBReader = DBCommand.ExecuteReader();
MessageBox.Show("New book record added to the system.", "Library System", MessageBoxButtons.OK);
while (DBReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// *** If you're going to be opening a connection be sure to close it ***
// *** Finally blocks work well for this ***
DBCon.Close();
this.txtName.ResetText();
this.txtAuthor.ResetText();
this.txtCategory.ResetText();
this.txtClassification.ResetText();
this.txtAvailabilityQuantity.ResetText();
this.txtPrice.ResetText();
}
}