簡體   English   中英

錯誤:對象必須實現 IConvertible

[英]Error : Object must implement IConvertible

當我收到以下錯誤時,我試圖將列表框項目和每個列表框項目的文本框值插入到數據庫中。

如果我嘗試僅插入列表框項目,我會成功,但是當我嘗試插入文本框值時,我收到此錯誤。 你能告訴我我做錯了什么嗎?

Error Message: Object must implement IConvertible.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Object must implement IConvertible.

Source Error:

Line 60: 
Line 61:             
Line 62:             cmd.ExecuteNonQuery();
Line 63: 
Line 64:

代碼

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

我想將列表框的所有值添加到數據庫中。

其次,即使我嘗試使用 .

所選項目

然后我收到以下錯誤。

Insert Error: Incorrect syntax near 'CPD1'. 
Incorrect syntax near 'CPD'. 
Incorrect syntax near 'CPD2'. 
Incorrect syntax near 'CPD'. 
Incorrect syntax near 'CPD3'. 
Incorrect syntax near 'CPD'.

知道我哪里出錯了嗎?

如果您的列表框只包含您需要更改以下行的字符串項目

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

當您收到 IConvertable 錯誤時,這意味着您已嘗試將一種類型分配給另一種類型。 在您的情況下,我想您已經嘗試將文本框分配給一個字符串。 文本框是一個對象。 您需要從中選擇值並將其轉換為 ToString()。

例如,如果您想將文本框分配給一個字符串,它看起來像這樣:

myString = Textbox1.Value.ToString();

IConvertable 是您有時可以使用的隱式 ToString()。 並非所有事情都已實施。 在您的情況下,對於您分配給字符串的每個控件,請驗證輸出將是您想要的字符串。 有些將實現 ToString() 並且它只是您正在使用的控件的指示器,而不是您期望的值。 查看每個項目並查看所需數據的存儲位置(通常在名為 Text 或 Value 的屬性中)。 然后驗證該輸出的數據類型。

我想添加這個是因為我今天遇到了這個錯誤消息,但它實際上只是掩蓋了一個更深層次的潛在問題。

我正在使用一些泛型和反射,在進一步挖掘后,實際錯誤是The type 'Microsoft.SqlServer.Types.SqlGeography' exists in both 'Microsoft.SqlServer.Types.dll' and 'Microsoft.SqlServer.Types.dll'

解決方案是對齊我的應用程序和依賴項之間引用的 DLL 的版本。 我通過從 Nuget 安裝特定版本來做到這一點,問題解決了! 如果這不是一個選項,您也許可以使用綁定重定向,但我還沒有嘗試過。

希望能幫助別人!

我已經能夠根據亞歷山大給出的建議解決這個問題。

請在下面找到正確的代碼。

感謝亞歷山大和所有其他人的幫助,特別是對花了很多時間的阿卜杜勒。

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

}

代替

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

我知道這有點舊,但是,如果有人正在尋找它,我還有另一個解決方案。

DB 中的 TIME 列和選擇查詢,我收到了類似的錯誤。 對於模型,我使用字符串作為時間類型。

只需在 SQL 類型 TIME 或任何類型的 VARCHAR(8) 或 VARCHAR(需要長度)中進行 CAST。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM