繁体   English   中英

将下拉列表值保存到SQL数据库条目

[英]Save dropdown list value to SQL Database Entry

我正在大学里做一个练习,我创建了一个SQL Database并在实体框架的帮助下将其链接到Visual Studio中的网格视图。 要在数据库上创建一个新条目,我必须填写一些文本字段(例如:名称,库存)。

现在,我知道从一个文本字段(取决于它是stringdecimal还是integer ,我使用以下内容将每个文本字段绑定到数据库表中的相应部分,并因此保存其value(.cs代码):

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

如果我想在代码中添加一个dropdown列表,然后从那里获取一个可用值并将其保存到给定表(类别)中正在创建的新条目中,我将如何完成以下代码行:

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

您的Rugby实体还应该具有FK属性( CategoryId ),这样您就可以保存下拉列表的SelectedValue来建立关系:

entry.CategoryId=dropdown.SelectedValue;

这是假设您以这种方式设置下拉列表:

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(); 

如果您已经将EF Diagrams引入Visual Studio(到.edmx文件中),并且我正确地理解了表结构,则可以这样简单地进行操作:

 // 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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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