错误:对象必须实现可逆的 IConvertible

本文关键字:IConvertible 实现 对象 错误 | 更新日期: 2023-09-27 17:56:22

当我收到以下错误时,我正在尝试将每个列表框项的列表框项和文本框值插入数据库。

如果我尝试仅插入列表框项,则成功了,但是当我尝试插入文本框值时,出现此错误。你能告诉我我做错了什么吗?

错误消息:对象必须实现 IConvertible。说明:执行当前 Web 请求期间发生未经处理的异常。请查看堆栈跟踪,了解有关错误及其在代码中起源位置的详细信息。异常详细信息:System.InvalidCastException:对象必须实现 IConvertible。源错误:第 60 行:第 61 行:            第 62 行:cmd.ExecuteNonQuery();第 63 行:第 64 行:

C# 代码

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
public partial class test1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    private string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["RM_Jan2011ConnectionString"].ConnectionString;
    }
    private void InsertRecords(StringCollection sc)
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        StringBuilder sb = new StringBuilder(string.Empty);

        foreach (string item in sc)
        {
            const string sqlStatement = "INSERT INTO FileID(File_Code, Dept_Code) VALUES(@File_Code, @Dept_Code)";
            sb.AppendFormat("{0}('{1}'); ", sqlStatement, item);
        }
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sb.ToString(), conn);

           cmd.Parameters.Add("@File_Code", SqlDbType.VarChar);
        cmd.Parameters["@File_Code"].Value = ListBox2.Items;

        cmd.Parameters.Add("@Dept_Code", SqlDbType.VarChar);
        cmd.Parameters["@Dept_Code"].Value = DropDownList1.Text;

            cmd.ExecuteNonQuery();

            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert ('Records Successfuly Saved!');", true);
        }

        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }
    }

    protected void Button4_Click(object sender, EventArgs e)
    {
        int myint = Convert.ToInt32(TextBox1.Text) + 1;
        for (int i = 1; i < myint; i++)
        {
            ListBox2.Items.Add(DropDownList1.SelectedItem.ToString() + i.ToString());
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        StringCollection sc = new StringCollection();
        foreach (ListItem item in ListBox2.Items)
        {
            {
                sc.Add(item.Text);
                sc.Add(DropDownList1.Text);
            }
        }
        InsertRecords(sc);
    }

我想将列表框的所有值添加到数据库中。

其次,即使我尝试使用.

选定项

然后我收到以下错误。

插入错误:"CPD1"附近的语法不正确。"CPD"附近的语法不正确。"CPD2"附近的语法不正确。"CPD"附近的语法不正确。"CPD3"附近的语法不正确。"CPD"附近的语法不正确。

知道我哪里出错了吗?

错误:对象必须实现可逆的 IConvertible

如果列表框仅包含字符串项,则需要更改以下行

cmd.Parameters["@File_Code"].Value = ListBox2.Items

cmd.Parameters["@File_Code"].Value = ListBox2.SelectedItem

如果项目是复杂对象,则添加 .ToString() 在最后

UPD:如果要添加所有ListBox项,则需要遍历其项集合并为每个项执行插入查询,如下所示:

foreach(string item in ListBox2.Items)
{
    SqlCommand cmd = new SqlCommand(sqlStatement, conn);       
    cmd.Parameters.Add("@File_Code", SqlDbType.VarChar);    
    cmd.Parameters["@File_Code"].Value = item;    
    cmd.Parameters.Add("@Dept_Code", SqlDbType.VarChar);    
    cmd.Parameters["@Dept_Code"].Value = DropDownList1.Text;        
    cmd.ExecuteNonQuery();
}

当您收到可逆转的错误时,这意味着您已尝试将一种类型分配给另一种类型。 在您的情况下,我想您已经尝试将文本框分配给字符串。 文本框是一个对象。 您需要从中选择值并转换该 ToString()。

例如,如果要将文本框分配给字符串,它将如下所示:

myString = Textbox1.Value.ToString();

IConvertable 是你有时可以使用的隐式 ToString()。 并非一切都实现了它。 在这种情况下,对于要分配给字符串的每个控件,请验证输出是否为所需的字符串。有些将实现 ToString(),它只是您正在使用的控件的指示器,而不是您期望的值。 查看每个项目,并查看所需数据的存储位置(通常在名为"文本"或"值"的属性中)。 然后验证该输出的数据类型。

我想

添加这个,因为我今天遇到了这个错误消息,但它实际上只是掩盖了一个更深层次的潜在问题。

我正在使用一些泛型和反射,在进一步挖掘后,实际错误The type 'Microsoft.SqlServer.Types.SqlGeography' exists in both 'Microsoft.SqlServer.Types.dll' and 'Microsoft.SqlServer.Types.dll'

解决方案是对齐在我的应用程序和依赖项之间引用的 DLL 版本。我通过从Nuget安装特定版本来做到这一点,问题解决了!如果这不是一个选项,您可能可以使用绑定重定向,但我还没有尝试过。

希望对别人有帮助!

而不是

cmd.Parameters["@File_Code"].Value = ListBox2.Items;

尝试做

cmd.Parameters["@File_Code"].Value = ListBox2.SelectedItem.Text;

因为ListBox.Items是一个集合,你需要一个特定的值而不是一组值。

错误的代码

foreach (string item in sc)
    {
        const string sqlStatement = "INSERT INTO FileID(File_Code, Dept_Code) VALUES(@File_Code, @Dept_Code)";
        sb.AppendFormat("{0}('{1}'); ", sqlStatement, item);
    }

string sqlStatement = string.Empty; 
foreach (string item in sc)
    {
        sqlStatement = "INSERT INTO FileID(File_Code, Dept_Code) VALUES({0}, {1})";
      sqlStatement = string.Format(sqlStatement, fileCodeVar, deptCodeVar);//let fileCodeVar is a variable containing fileCode and DeptCodeVar is a variable containing DeptCode
    }

取代

SqlCommand cmd = new SqlCommand(sb.ToString(), conn);

 SqlCommand cmd = new SqlCommand(sqlStatement, conn);

我已经能够根据亚历山大给出的建议解决问题。

请在下面找到正确的代码。

感谢亚历山大和所有其他人的帮助,特别是对阿卜杜勒的帮助,他花了很多时间。

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
public partial class FileIDmasterWorking : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button4_Click(object sender, EventArgs e)
    {
        int myint = Convert.ToInt32(TextBox1.Text) + 1;
        for (int i = 1; i < myint; i++)
        {
            Convert.ToString(ListBox2.Items);
            ListBox2.Items.Add(DropDownList1.SelectedItem.ToString() + i.ToString());
        }
    }
    private string GetConnectionString()
    {
        return     System.Configuration.ConfigurationManager.ConnectionStrings["RM_Jan2011ConnectionString"].ConnectionString;
    }
    private void InsertRecords(StringCollection sc)
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        StringBuilder sb = new StringBuilder(string.Empty);
        **foreach (ListItem item in ListBox2.Items)
        {
            const string sqlStatement = "INSERT INTO FileID(File_Code, Dept_Code) VALUES(@File_Code, @Dept_Code)";
            sb.AppendFormat("{0}('{1}'); ", sqlStatement, item);
            SqlCommand cmd = new SqlCommand(sqlStatement, conn);
            cmd.Parameters.Add("@File_Code", SqlDbType.VarChar);
            cmd.Parameters["@File_Code"].Value = item.ToString();
            cmd.Parameters.Add("@Dept_Code", SqlDbType.VarChar);
            cmd.Parameters["@Dept_Code"].Value = DropDownList1.Text;
            conn.Open();
            cmd.ExecuteNonQuery();**
            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
            conn.Close();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        StringCollection sc = new StringCollection();
        foreach (ListItem item in ListBox2.Items)
        {
            {
                sc.Add(item.Text);
            }
        }
        InsertRecords(sc);
    }
}
我知道

这有点旧了,但是,如果有人正在寻找它,我有另一种解决方案。

数据库中的TIME列并选择查询,我收到了类似的错误。对于模型,我使用字符串作为时间类型。

只需在 SQL 类型 TIME 或任何类型中转换 VARCHAR(8) 或 VARCHAR(length-need)。