0

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();
        }
    }
avner1169
  • 41
  • 6

3 Answers3

0

Create an enum for your categories, for example:

enum BookCategory
{
    Science=1,
    Art,
    Romance,
    History
}

Then you can write:

if(Enum.TryParse<BookCategory>(txtCategory.Text.Trim(), out BookCategory categoryId))
    Console.WriteLine((int)categoryId);
else
    Console.WriteLine("Category not recognised");

Which will print 4 if txtCategory contains "History".

iakobski
  • 1,000
  • 7
  • 8
0

If I understand your question correctly, there are different approaches for what you're trying to achieve. Where do you want that 'enum' to originate from? You can actually make an enum with categories and their respectable value, and display it to the user to chose from, like:

public enum Categories
{
   SciFi = 1,
   ...
   History = 4,
   ...
}

as iakobski answered, and you can also get these categories from a database (thus, making them dynamic, e.g. you can add and remove categories from the list without the need to change static code, compile it and re-deploy). Usually, the common practice in most cases is indeed storing such values in a database, in a table with columns of an ID and CategoryName.

ShayLivyatan
  • 103
  • 7
  • Thank you both for advising - Yes, that is what I want (and I'm also working with a Database yes). My other question is - Does the enum need to be implemented within the Save Button Method, or outside of it, please? – avner1169 May 19 '19 at 11:11
  • @avner1169 well it depends on how you're going to use it. Common practice is always to lean towards re-usability, so the functionality should be outside the `btnSave_Click` method, so you could use it in more places and not just there, but if you're not intending on using it elsewhere, I guess it can be inside that method. Basically it depends on you... – ShayLivyatan May 19 '19 at 11:14
0

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.

Unless you have business rules tied to specific emum values, I suggest to don't hard-code the values in the application and instead load the category name and id values from a database Category table. That can also ensure data integrity with a foreign key relationship to the Book table and allow new categories to be added without code changes.

A better user experience would be a combobox/list that the users to select from by name instead of free-form text box. The code can then use the id of the selected value without additional validation or lookup for the insert and the database.

On a separate note, use parameterized queries to improve performance and security. One should never build SQL queries using string concatenation from untrusted sources.

Dan Guzman
  • 43,250
  • 3
  • 46
  • 71