简体   繁体   中英

Save dropdown list value to SQL Database Entry

I'm doing an exercise for university where I have created a SQL Database and linked it to a grid view in Visual Studio with help of Entity Framework. To create a new entry on the database I have to fill some text fields (eg: Name, Stock).

Now, I know that from a text field, depending on it being string , decimal or integer , I use the following to bind each text field to the respective section on the table in the database and therefore save its value(.cs code):

Rugby entry = new Rugby();
entry.Stock = int.Parse(txtStock.Text);
entry.Name = txtName.Text;

If I want to add a dropdown list to my code and from there take one of the values available and save it to new entry being created in the given table (Category), how would I complete the following bit line of code:

entry.Category=???(bit that I don't know how to complete)

Your Rugby entity should also have FK property ( CategoryId ), this way you are able to save the SelectedValue of your dropdown list to establish the relationship:

entry.CategoryId=dropdown.SelectedValue;

This is assuming you are setting your dropdown list like this way:

var categories = (from c in context.Categories
                            select new { c.CategoryId, c.CategoryName }).ToList();

// Change this for the real property names
dropdown.DataValueField = "CategoryId";
dropdown.DataTextField = "CategoryName";
dropdown.DataSource = categories;
dropdown.DataBind(); 

If you have already brought in your EF Diagrams into Visual Studio (to your .edmx files), and I am understanding your table structures correctly you can simply do it like this:

 // This will be what you named your entities from your .edmx
 // This object sets up the connection to your entities 
 public static myEntities _db = new myEntities ();

(Auto-Generated Class via .edmx)
// When you add an .edmx file (database diagram for EF)
// There is an auto-generated class you are able to use - 
// We are setting this up below.
EF_Class_Name newDbEntry= new EF_Class_Name();


// You can access any property of the class just like any other object
// property.
newDbEntry.Stock = int.Parse(txtStock.Text);
newDbEntry.Name = txtName.Text;
newDbEntry.Category = dropdown.SelectedValue;


// Add your new data (essentially an insert)
_db.EF_Class_Name.Add(newDbEntry);

// Commit the changes
_db.SaveChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM