首页 > 解决方案 > 无法将下拉菜单中的项目插入我的数据库

问题描述

我是 C# 新手,我正在尝试将一些值插入到我在 Visual Studio 中创建的数据库中。

-我正在创建一个食谱应用程序-所以在表单中我有一些组件,例如文本框(用于标题、成分、描述)、一个下拉项(组合框)来指定它是食物还是甜食,以及一个插入所有这些数据的按钮进入我的数据库。

当我按下按钮时,我可以将所有内容(所有文本框)添加到数据库中,但下拉值除外。

这是button_click里面的代码

       private void addItemButton_Click(object sender, EventArgs e)
    {

        string dat = "Insert into [Table](Title,Category,Ingredients,Description) Values('" + titleTextBox.Text + "','" + dropdownCategory.SelectedValue + "','" + addIngredientTextBox.Text + "','" + addDescriptionTextBox.Text + "')";
        SqlConnection sqlCon = new SqlConnection(connectionString);
        SqlCommand sqlCmd = new SqlCommand(dat, sqlCon);
        sqlCon.Open();
        sqlCmd.ExecuteNonQuery();
        sqlCon.Close();
    }

标签: c#mysqlvisual-studio

解决方案


我做了一个代码示例,它可以成功地将组合框值插入到数据库中。

  public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string dat = string.Format("Insert into [Sample](Title,Category,Ingredients,Description)values('{0}','{1}','{2}','{3}')", textBox1.Text, comboBox1.SelectedItem,textBox2.Text,textBox3.Text);
            string connectionString = @"connectionstring";
            SqlConnection sqlCon = new SqlConnection(connectionString);
            SqlCommand sqlCmd = new SqlCommand(dat, sqlCon);
            sqlCon.Open();
            sqlCmd.ExecuteNonQuery();
            sqlCon.Close();
            MessageBox.Show("success");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.AddRange(new object[] { "basketball","football", "volleyball" });

        }
    }

推荐阅读