简体   繁体   English

C#在小int列中插入组合框项目索引

[英]C# insert combo box item index in small int column

I want to insert the selected item index from a combobox into a tinyint column ( FoodType ) in SQL Server. 我想将组合框中的选定项目索引插入SQL Server中的tinyint列( FoodType )中。 I wrote the code below, but I get an exception: 我写了下面的代码,但出现异常:

Must declare the scalar variable @fType 必须声明标量变量@fType

What must I do? 我必须做什么?

string query = "INSERT INTO MenuTbl (FoodName,FoodType,FoodUnit, SalePrice)" +
               "VALUES (@fName, @fType, @fUnit, @fPrice)";

connection = new SqlConnection(conectionString);

SqlCommand cmd = new SqlCommand(query,connection);
cmd.Parameters.AddWithValue("@fName", FNameTextBox.Text.Trim());
cmd.Parameters.AddWithValue("@fTyp", TypeComboBox.SelectedIndex + 1);
cmd.Parameters.AddWithValue("@funit", UnitComboBox.SelectedIndex +1);
cmd.Parameters.AddWithValue("@fprice", int.Parse(PriceEdit.Text));

connection.Open();
cmd.ExecuteNonQuery();
connection.Close();

I think you made a typo with this line of code 我想您用这行代码打错了

cmd.Parameters.AddWithValue("@fTyp", TypeComboBox.SelectedIndex + 1);

It should be @fType atleast according to your select query 根据您的选择查询,它应至少为@fType

 string query = "Insert into MenuTbl (FoodName,FoodType,FoodUnit, SalePrice)" +
         "VALUES (@fName,@fType,@fUnit, @fPrice)";

And I also think that TypeComboBox.SelectedIndex + 1 will only give you the index+1 numerical value rather than the selected text contents. 而且我还认为TypeComboBox.SelectedIndex + 1只会为您提供index + 1数值,而不是所选文本内容。 Is that what you want? 那是你要的吗?

您是否在参数上缺少“ e”?

cmd.Parameters.AddWithValue("@fTyp", TypeComboBox.SelectedIndex + 1);

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

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