相关疑难解决方法(0)

的ExecuteScalar(); 使用scope_identity()生成"System.InvalidCastException:指定的强制转换无效"

我有一个接受各种数据的表单(通过文本框和复选框列表),在click事件中,他们将所有数据插入表中并选择scope_identity,然后将其存储在变量中,以便在插入checkboxlist项时使用它使用循环到另一个表

根据许多答案和例子,这应该完美!但它给了我这个错误:

Exception Details: System.InvalidCastException: Specified cast is not valid.

Line 66:             int NewBrandId = (int)comm.ExecuteScalar(); 
Run Code Online (Sandbox Code Playgroud)

这是我的linkbutton方法代码:

   protected void lnkbtnUploadAndSubmit_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MOODbCenterConnection"].ConnectionString);

        SqlCommand comm = new SqlCommand("INSERT INTO Brands (BrandName, BrandLogo, BrandWebsite, IsBrandVisible) VALUES (@Name, @Logo, @Website, @IsVisible); SELECT scope_identity();", conn);

        comm.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar, 50);
        comm.Parameters["@Name"].Value = txtbxBrandName.Text;

        comm.Parameters.Add("@Logo", System.Data.SqlDbType.Text);
        comm.Parameters["@Logo"].Value = fileuploadLogo.PostedFile.FileName;

        comm.Parameters.Add("@Website", System.Data.SqlDbType.Text);
        comm.Parameters["@Website"].Value = txtbxWebsite.Text;

        comm.Parameters.Add("@IsVisible", System.Data.SqlDbType.Bit);
        comm.Parameters["@IsVisible"].Value = chkbxIsPublished.Checked;
        conn.Open();


        int NewBrandId = (int)comm.ExecuteScalar(); 

        conn.Close();

        foreach (ListItem li in chkbxlstCuisines.Items) …
Run Code Online (Sandbox Code Playgroud)

c# sql asp.net ado.net webforms

18
推荐指数
2
解决办法
2万
查看次数

获取新的SQL记录ID

如何获取刚刚插入的新记录的自动生成ID?(使用ASP classic和MSSQL 2005)

sql sql-server sql-server-2005 asp-classic

10
推荐指数
4
解决办法
2万
查看次数