简体   繁体   English

将DropDownList值插入表

[英]Inserting DropDownList value to table

I have a database table with two int columns: GameID and GenreID where GameID is the identity column. 我有一个带有两个int列的数据库表:GameID和GenreID,其中GameID是标识列。 I want to insert the SelectedValue from my DropDownList into the table as GenreID using ASP.NET and C#. 我想使用ASP.NET和C#将我的DropDownList中的SelectedValue作为GenreID插入表中。 All my ListItems in the DropDownList look something like this: 我在DropDownList中的所有ListItem看起来都像这样:

<asp:ListItem Text="Action" Value="1"></asp:ListItem>

So, here's what I'm trying to do. 所以,这就是我想要做的。

Converting the DropDownList value to int: 将DropDownList值转换为int:

int GenreID = Int32.Parse(DropDownGenre.SelectedValue);

The SQL command: SQL命令:

SqlCommand cmd2 = new SqlCommand("INSERT into Games_Genres values(@GenreID)");

And adding that value to the parameter: 并将该值添加到参数中:

cmd2.Parameters.AddWithValue("@GenreID", SqlDbType.Int).Value = GenreID;

This gives me the following error: 这给了我以下错误:

String or binary data would be truncated. 字符串或二进制数据将被截断。 The statement has been terminated. 该语句已终止。

I understand that this error usually (always?) means that the field isn't big enough to hold the data I'm trying to insert. 我知道这个错误通常(总是?)意味着该字段的大小不足以容纳我要插入的数据。 However, seeing that I converted the value to int I don't get why that is a problem? 但是,看到我将值转换为int,我不明白为什么这是一个问题?

Can you try 你能试一下吗

cmd2.Parameters.Add("@GenreID", SqlDbType.Int); cmd2.Parameters["@GenreID"].Value = GenreID;

Instead? 代替?

Can you try 你能试一下吗

SqlCommand cmd2 = 
      new SqlCommand("INSERT into Games_Genres (GenreID) values(@GenreID)");

Is GenreID also set as an identity column? GenreID是否也设置为标识列?

Also, when creating parameters for a query you don't need to specify the type because T-SQL implicitly converts types. 同样,在为查询创建参数时,您无需指定类型,因为T-SQL隐式转换类型。 It should look like: 它应该看起来像:

using (SqlCommand cmd2 = new SqlCommand("INSERT into Games_Genres (GenreID) values (@GenreID)"))
{
    cmd2.Parameters.AddWithValue("@GenreID", GenreID);
    cmd2.ExecuteScalar();
}

我还不能添加注释,因此,您的架构图像将GameId显示为其一个关键字段,并且您未设置它,如果您对它添加了参数,也可能会创建一个存储过程而不是文本查询(如果仅用于测试)目的为何不尝试:

var sqlCommand = new SqlCommand(String.Format("INSERT into Games_Genres values({0})", genreId));

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

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