c# - 无法将下拉菜单中的项目插入我的数据库
问题描述
我是 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();
}
解决方案
我做了一个代码示例,它可以成功地将组合框值插入到数据库中。
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" });
}
}
推荐阅读
- python - 对模型类的 __init__ 方法的更改似乎没有生效
- javascript - 如何将 GLSL 比例和位置与 VideoContext 一起使用?
- java - 我如何在 Java 中验证日期(仅当前日期或之后)
- jquery - 关于 Laravel Webpack Mix 和提取方法
- r - R - dplyr 中的代码行运行时间
- unix - 使用 find 命令但收到错误“路径必须在表达式之前”
- python - Pandas drop_duplicates -> 致命的 Python 错误:释放无
- c - 尝试分配内存时的 sysmalloc
- javascript - MERN Stack - TypeError:无法将未定义或 null 转换为对象
- r - R:postgres 连接不断超时或中断