【问题标题】:Error : Object must implement IConvertible错误:对象必须实现 IConvertible
【发布时间】:2011-05-11 15:32:09
【问题描述】:

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

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

错误消息:对象必须实现 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”附近的语法不正确。

知道我哪里出错了吗?

【问题讨论】:

  • Aditya,您应该在答案中添加评论,而不是编辑它们。我已经拒绝了你的两个这样的编辑。

标签: c# iconvertible


【解决方案1】:

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

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

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

如果 items 是复杂对象,则在末尾添加 .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();
}

【讨论】:

  • 感谢亚历山大的回复。现在首先,如果我想将列表框的所有值添加到数据库中。其次,即使我尝试使用 .SelectedItem 也会收到以下错误。插入错误:“CPD1”附近的语法不正确。 “CPD”附近的语法不正确。 “CPD2”附近的语法不正确。 “CPD”附近的语法不正确。 “CPD3”附近的语法不正确。 “CPD”附近的语法不正确。知道我哪里出错了
【解决方案2】:

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

例如,如果你想将你的文本框分配给一个字符串,它看起来像这样:

myString = Textbox1.Value.ToString();

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

【讨论】:

  • 比格斯感谢您的回复。在我的消息中,我说过文本框。很抱歉,它不是文本框,而是我要添加的下拉列表值。
【解决方案3】:

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

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

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

希望对其他人有所帮助!

【讨论】:

    【解决方案4】:

    代替

    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);
    

    【讨论】:

    • 我想将列表框的所有值添加到数据库中。其次,即使我尝试使用 . SelectedItem 然后我收到以下错误。插入错误:“CPD1”附近的语法不正确。 “CPD”附近的语法不正确。 “CPD2”附近的语法不正确。 “CPD”附近的语法不正确。 “CPD3”附近的语法不正确。 “CPD”附近的语法不正确。知道我哪里出错了
    • 感谢您提供的帮助。我在这个问题上挣扎了将近一个星期。这就是我所做的,我收到一个错误.....ExecuteNonQuery:CommandText 属性尚未初始化......你能帮忙请 string fileCodeVar = "ListBox2.Items";字符串 DeptCodeVar = "Dropdownlist1.Text"; foreach (sc 中的字符串项) { string sqlStatement = "INSERT INTO FileID(File_Code, Dept_Code) VALUES({0}, {1})"; string.Format(sqlStatement, fileCodeVar, DeptCodeVar);
    • 如果您觉得有帮助,请将其标记为答案。
    • 肯定会做 Abdul Bhai 但问题没有解决。这就是我所做的,我收到一个错误.....ExecuteNonQuery:CommandText 属性尚未初始化......你能帮忙请 string fileCodeVar = "ListBox2.Items";字符串 DeptCodeVar = "Dropdownlist1.Text"; foreach (sc 中的字符串项) { string sqlStatement = "INSERT INTO FileID(File_Code, Dept_Code) VALUES({0}, {1})"; string.Format(sqlStatement, fileCodeVar, DeptCodeVar);
    • 你告诉我的错误信息是不言自明的,没关系,我已经更新了答案,希望你这次能解决。
    【解决方案5】:

    根据 Alexander 的建议,我已经能够解决问题。

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

    感谢 Alexander 和所有其他人特别为花费大量时间的 Abdul 提供的帮助。

    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);
        }
    
    }
    

    【讨论】:

    • 我建议你给他答案?
    【解决方案6】:

    我知道这有点老了,但是,如果有人在寻找它,我还有另一个解决方案。

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

    在 SQL 类型 TIME 或任何类型如 VARCHAR(8) 或 VARCHAR(需要长度) 中简单地 CAST。

    【讨论】:

      最近更新 更多