首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将Combobox (下拉列表)作为新数据库记录的一部分实现

将Combobox (下拉列表)作为新数据库记录的一部分实现
EN

Stack Overflow用户
提问于 2019-05-21 03:25:34
回答 1查看 37关注 0票数 0

我有一个本地数据库,它已经有记录了。我目前正在进行一个图书馆项目,并有两个图书和类别表(类别也在图书表中的FK )在DB中。

在Windows Forms应用程序中,我正在尝试实现一个表单,以便在books表中插入新的图书记录,并在选择类别时使用组合框。

到目前为止,我已经尝试过以下代码-按下保存按钮确实会在DB中生成表单中给出的详细信息,但Category值始终为NULL (combobox不起作用)。

你能帮我找出我在下面的实现中遗漏了什么吗?下面的代码是我为一个Category ID做的测试--Getters和Setters已经实现了。

编辑下面的更多细节-请注意,我知道并仍然需要使用参数化查询,在我对这个组合框问题进行分类后,我将研究它。

代码语言:javascript
复制
 private void AddBookRecordForm_Load(object sender, EventArgs e)
    {
        var dataSource = new List<Category>();

        dataSource.Add(new Category() { CategoryID = '4', CategoryName = "History" });

        cbCategory.ValueMember = "CategoryID";
        cbCategory.DisplayMember = "CategoryName";
        cbCategory.DataSource = dataSource;
    }

编辑:

代码语言:javascript
复制
 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, BookAvailabilityQuantity, Price) values ('" + this.txtName.Text.Trim() 
    + "','" + this.txtAuthor.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.txtAvailabilityQuantity.ResetText();
    this.txtPrice.ResetText();
}
EN

回答 1

Stack Overflow用户

发布于 2019-05-21 03:31:58

数据源可以提供控件中的项,但选择新项不会像更改绑定文本框中的值那样自动更改数据值。您需要手动获取所选值并更新更新记录中的相应字段。请参阅this post。

代码语言:javascript
复制
String Query = "insert into Books (CategoryName, BookName, BookAuthor, BookAvailabilityQuantity, Price) values (
    "'" + cbCategory.Text
    + "','" + this.txtName.Text.Trim() 
    + "','" + this.txtAuthor.Text.Trim() 
    + "','" + this.txtAvailabilityQuantity.Text.Trim() 
    + "','" + this.txtPrice.Text.Trim() + "');";
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56226996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档