![](/img/trans.png)
[英]how to populate combo box from database and insert new item on index zero in C#
[英]C# insert combo box item index in small int column
我想將組合框中的選定項目索引插入SQL Server中的tinyint
列( FoodType
)中。 我寫了下面的代碼,但出現異常:
必須聲明標量變量@fType
我必須做什么?
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();
我想您用這行代碼打錯了
cmd.Parameters.AddWithValue("@fTyp", TypeComboBox.SelectedIndex + 1);
根據您的選擇查詢,它應至少為@fType
string query = "Insert into MenuTbl (FoodName,FoodType,FoodUnit, SalePrice)" +
"VALUES (@fName,@fType,@fUnit, @fPrice)";
而且我還認為TypeComboBox.SelectedIndex + 1
只會為您提供index + 1數值,而不是所選文本內容。 那是你要的嗎?
您是否在參數上缺少“ e”?
cmd.Parameters.AddWithValue("@fTyp", TypeComboBox.SelectedIndex + 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.