2011-05-11 139 views
3

我想爲每個列表框項目插入列表框項目和一個文本框值到數據庫,當我得到下面的錯誤。錯誤:對象必須實現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: 

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

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

Secondlly即使我嘗試使用。

SelectedItem

然後我得到以下錯誤。

 
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'. 

任何想法我錯了嗎?

+1

Aditya,你應該添加*評論*的答案,而不是*編輯*他們。我已經拒絕了您的這兩個編輯。 – 2011-05-11 16:52:05

回答

2

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

例如,如果你想分配您的文本框爲一個字符串,它應該是這樣的:

myString = Textbox1.Value.ToString(); 

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

+0

Biggs感謝您的回覆。在我的消息中我說過Textbox。我很抱歉,它不是一個文本框,而是我想添加的一個下拉列表值。 – Aditya 2011-05-11 16:31:31

6

如果你的列表框只包含字符串的項目,你需要下面的行

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

更改爲

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

如果項目是複雜的對象在年底

UPD添加的ToString() :如果您想要添加所有ListBox項目,您需要循環訪問其項目集合並執行插入查詢foreach項目,如下所示:

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

感謝您的回覆亞歷山大。現在首先,如果我想將列表框的所有值添加到數據庫中。 Secondlly即使我嘗試使用.SelectedItem,然後我得到以下錯誤。插入錯誤:「CPD1」附近的語法錯誤。 「CPD」附近的語法錯誤。 「CPD2」附近的語法錯誤。 「CPD」附近的語法錯誤。 「CPD3」附近的語法錯誤。 「CPD」附近的語法錯誤。任何想法Iam出錯 – Aditya 2011-05-11 16:36:51

0

而不是

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

我想將列表框的所有值添加到數據庫。 Secondlly即使我嘗試使用。 SelectedItem 然後我得到以下錯誤。 插入錯誤:「CPD1」附近的語法不正確。 「CPD」附近的語法錯誤。 「CPD2」附近的語法錯誤。 「CPD」附近的語法錯誤。 「CPD3」附近的語法錯誤。 「CPD」附近的語法錯誤。 Iam出錯的任何想法 – Aditya 2011-05-11 17:00:15

+0

這意味着你沒有正確構建查詢。 – 2011-05-11 17:05:29

+0

感謝您提供的幫助。我現在正在爲這個星期的一週苦苦掙扎。這是我所做的,我得到一個錯誤..... ExecuteNonQuery:CommandText屬性尚未初始化...你能幫忙請字符串fileCodeVar =「ListBox2.Items」; 字符串DeptCodeVar =「Dropdownlist1。文本「; 的foreach(在SC串項目) { 串的SQLStatement = 」INSERT INTO寫到FileID(File_Code,Dept_Code)VALUES({0},{1})「; 的String.Format(的SQLStatement,fileCodeVar,DeptCodeVar ); – Aditya 2011-05-11 17:43:59

1

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

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

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

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

} 
+1

我建議你給他答案呢? – Ted 2011-08-02 07:48:30

0

我想補充一點,因爲我今天遇到了這個錯誤信息,但它實際上只是掩蓋了一個更深層次的潛在問題。

我正在使用一些仿製藥和反射,並在進一步挖掘後發現實際錯誤爲The type 'Microsoft.SqlServer.Types.SqlGeography' exists in both 'Microsoft.SqlServer.Types.dll' and 'Microsoft.SqlServer.Types.dll'

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

希望能幫助別人!

相關問題