SelectedIndex未插入正确的值

时间:2013-11-18 17:29:24

标签: c# sql sql-server tsql combobox

我有一种方法可以将用户信息插入SQL Server数据库。我在pageload事件中填充了我的组合框。用户选择他们想要的输入,如果他们正在更新旧记录,则点击更新,如果创建新记录则插入更新。当他们这样做时我的数据库没有存储正确的值,如果他们选择4存储3.这是我的插入方法和填充方法。

插入方法:我必须加入StockID,因为它是主键。

using (dbConn2 = new SqlConnection(Properties.Settings.Default["tville"].ToString()))
{
   SqlCommand addNewFormat = new SqlCommand(@"INSERT INTO PackLabelFormat ( PackFormatID, Description, PrintWeight, PrintPlantCode, PrintPrice, StockID) VALUES (@PackFormatID, @Description, @PrintWeight, @PrintPlantCode, @PrintPrice, (SELECT @StockID from LabelStockReference LSR WHERE LSR.StockID = @StockID))", dbConn2);

   addNewFormat.Parameters.AddWithValue("@PackFormatID", Convert.ToInt32(IDselect));
   addNewFormat.Parameters.AddWithValue("@Description", rTxtBoxDescription.Text);
   addNewFormat.Parameters.AddWithValue("@PrintPrice", rChkBoxPrintPrice.Checked);
   addNewFormat.Parameters.AddWithValue("@PrintWeight", rChkBoxWeight.Checked);
   addNewFormat.Parameters.AddWithValue("@PrintPlantCode", rChkBoxPlantCode.Checked);
   addNewFormat.Parameters.AddWithValue("@StockID", Convert.ToInt32(cmboBoxStock.SelectedIndex));

   dbConn2.Open();
   addNewFormat.ExecuteNonQuery();

填充方法:

if (labelList != null)
{
   foreach (LabelData l in labelList)
   {
       cmboBoxStock.Items.Add(string.Format("{0} - {1}", l.PackFormatID, l.Description));
   }
}

如果还有什么我要离开的,请告诉我。感谢。

2 个答案:

答案 0 :(得分:1)

INSERT语句有两个选项:

(1)您可以使用INSERT ... VALUES ....,在这种情况下,您必须提供与要插入数据的列一样多的值,并且您必须提供文字值或仅限SQL Server变量 - 您无法使用SELECT提供值:

 DECLARE @ASqlServerVariable VARCHAR(100)
 SET @ASqlServerVariable = 'any possible value that's legal for this datatype'

 INSERT INTO dbo.YourTable(ID, Col1, Col2, Col3) 
 VALUES (42, 'Some fixed value', @ASqlServerVariable, 'Another literal value')

可以做的是使用SELECT将您感兴趣的值存储到SQL Server变量中:

DECLARe @StockID INT

SELECT @StockID = ID 
FROM dbo.LabelStockReference LSR 
WHERE LSR.StockID = 4711

(2)如果您无法提供所有文字值或变量,则必须使用INSERT .... SELECT ...选项,这需要您在{{1}中提供尽可能多的列因为SELECT期望在目标表中插入一行:

INSERT

有关所有可能选项等的所有详细信息和确切语法,请参阅official TechNet documentation for INSERT

答案 1 :(得分:0)

第一个SelectedIndex为0,您的第一个ID为1,所以只需进行此更改:

addNewFormat.Parameters.AddWithValue("@StockID", Convert.ToInt32(cmboBoxStock.SelectedIndex)+1);
相关问题