简体   繁体   中英

Inserting DropDownList value to table

I have a database table with two int columns: GameID and GenreID where GameID is the identity column. I want to insert the SelectedValue from my DropDownList into the table as GenreID using ASP.NET and C#. All my ListItems in the DropDownList look something like this:

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

So, here's what I'm trying to do.

Converting the DropDownList value to int:

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

The SQL command:

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?

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?

Also, when creating parameters for a query you don't need to specify the type because T-SQL implicitly converts types. 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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