繁体   English   中英

SelectedIndex没有插入正确的值

[英]SelectedIndex not inserting correct value

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

插入方法:我必须加入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));
   }
}

如果还有其他遗漏,请告诉我。 谢谢。

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 ...选项,该选项要求您在SELECT提供与INSERT希望插入的行一样多的列进入目标表:

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

 INSERT INTO dbo.YourTable(ID, Col1, Col2, Col3) 
    SELECT 
        42, 'Some fixed value', @ASqlServerVariable, aTableColumn
    FROM
        dbo.SomeOtherTable

有关所有详细信息以及所有可能选项的确切语法,请参阅INSERT官方TechNet文档

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

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

暂无
暂无

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

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