繁体   English   中英

如何处理异常不允许从数据类型varchar隐式转换为varbinary(max)。 在将数据添加到数据库时

[英]how to handle the exception Implicit conversion from data type varchar to varbinary(max) is not allowed. while adding the data to database

在我的应用程序中,我需要向数据库中添加数据并将其显示在gridview中,下面是我不添加id即可使用的代码,它可以正常工作,但是在我的插入查询和更新查询中添加了id之后,我Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.获取了此异常Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. 我是新来的人,我该如何处理该异常

protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection cnn = new SqlConnection();
        cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconnection "].ConnectionString;
        cnn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "select * from  TableName";
        cmd.Connection = cnn;
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        DataSet ds = new DataSet();
        da.Fill(ds, " TableName ");
        SqlCommandBuilder cb = new SqlCommandBuilder(da);
        DataRow drow = ds.Tables["TableName"].NewRow();
        drow["id"] = TextBox1.Text;
        drow["Name"] = TextBox2.Text;
        drow["Designation"] = TextBox3.Text;
        drow["Mobile_No"] = TextBox4.Text;
        drow["Address"] = TextBox5.Text;

        ds.Tables["TableName "].Rows.Add(drow);
        da.Update(ds, " TableName ");
        string script = @"<script language=""javascript"">
        alert('Information have been Saved Successfully.......!!!!!.');
       </script>;";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
    }

由于Id很可能是数字值,因此请勿尝试为其分配字符串值,而应为该数字生成SQL代码:

"[...]values(" + Id + ",'" + [...]

而不是(请注意'符号)

"[...]values('" + Id + "','" + [...]

但是,正如Damien_The_Unbeliever指出的那样,您应该使用SQL参数而不是将整个语句写为字符串。

如果您将Id值定义为自动分配的身份列,则只需将其从语句的值列表中删除即可。

例外是不允许从数据类型varchar隐式转换为varbinary(max)。 使用CONVERT函数运行此查询。

因此,Sql Server表列和C#id列都必须为varchar或varbinary。 VarBinary(sqltype)= Byte [](.Net)

    byte[] ID=SqlDbType.VarBinary;
    string query = "insert into RegistrationDetails1(Id,FirstName,LastName,MiddleName,Email,LoginID,CreatedDate,Role,Password,Activestatus,passwordstatus,Dept,Eno,Customer) values('" + ID + "','" + txtfname.Text + "','" + txtlname.Text + "','" + txtmname.Text + "','" + txtEmail.Text + "','" + LoginId[0].ToString() + "','" + DateTime.Now + "','" + ddlRole.SelectedItem.ToString() + "','" + Password + "','" + "1" + "','" + "1" + "','" + Dept + "','" + txteno.Text + "','" + Customer + "')";

暂无
暂无

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

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