将所选文本从下拉框保存到数据库时,列名称错误无效

时间:2012-04-06 09:44:32

标签: c# sql-server database ado.net

使用的平台:Microsoft Visual Studio 2010(C#)
数据库:SQL Server 2008 R2 Express

我想从下拉列表中获取文本并将其放入数据库表中。我收到错误说

  

无效的列名称“类型”。

虽然列存在于数据库表中。

da.InsertCommand = new SqlCommand("insert into tblProductMaster ([Name],[Type],[Height],[Width],[Length],[Price]) values( @Name , @Type , @Height , @Width , @Length , @Price )", con);

da.InsertCommand.Parameters.Add("@Name", SqlDbType.VarChar).Value = txtName.Text;
da.InsertCommand.Parameters.Add("@Type", SqlDbType.VarChar, 10).Value = ddlType.SelectedItem.ToString();
da.InsertCommand.Parameters.Add("@Height", SqlDbType.Float).Value = float.Parse(txtHeight.Text);
da.InsertCommand.Parameters.Add("@Width", SqlDbType.Float).Value = float.Parse(txtWidth.Text);
da.InsertCommand.Parameters.Add("@Length", SqlDbType.Float).Value = float.Parse(txtLength.Text);
da.InsertCommand.Parameters.Add("@Price", SqlDbType.SmallMoney).Value = int.Parse(txtPrice.Text);

da.InsertCommand.ExecuteNonQuery();

2 个答案:

答案 0 :(得分:2)

我认为您的问题是您使用的是SQL Server reserved word ("Size"),并且未将其正确封装在INSERT声明中。

试试这个:

da.InsertCommand = new SqlCommand("insert into tblProductMaster ([Name], [Size], [Height], [Width], [Length], [Price]) values(@Name, @Size, @Height, @Width, @Length, @Price)", con);

请注意[&列名称周围的] ...这将告诉SQL Server将它们视为列。

警告:高度建议您更改这些列名称(如果可以)。使用任何产品的保留字是非常差的数据库设计,并将继续导致您的问题和/或额外的工作。最好早点解决它。

答案 1 :(得分:0)

@Sagar试试这个

string strCmd = @"insert into tblProductMaster ([Name], [Size], [Height], [Width], [Length], [Price]) values(@Name, @Size, @Height, @Width, @Length, @Price)";  

然后

SqlCommand cmd = new SqlCommand(strCmd, con);  
cmd.Parameters.Add("@Size", SqlDbType.VarChar, 10, ddlSize.SelectedItem.Value.ToString());  

da.InsertCommand = cmd;