6

I am trying to insert Listbox Items and a Textbox value for each of the listbox items to the database when I get the below error.

IF i try to insert the list box items only I am successful but when i try to insert the textbox value I get this error. Can you please tell me what I am doing wrong.

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# CODE

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

I want to add all the values of the listbox to the database.

Secondlly even if I try to use .

SelectedItem

then I get the following error.

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

Any idea where I am going wrong?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Aditya
  • 71
  • 1
  • 1
  • 4
  • 2
    Aditya, you should add *Comments* to answers instead of *Editing* them. I've rejected two such edits of yours already. – Ates Goral May 11 '11 at 16:52

6 Answers6

6

if your listbox contains only string items you need to change following line

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

to

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

if items is complex objects add .ToString() at the end

UPD: if you want to add all ListBox items you need to loop through its item collection and execute insert query foreach item, something like this:

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();
}
Alexander
  • 1,287
  • 1
  • 15
  • 34
  • Thanks for your reply Alexander. Now firstly if I want to add all the values of the listbox to the database. Secondlly even if I try to use .SelectedItem then I get the following error. 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'. any idea where Iam going wrong – Aditya May 11 '11 at 16:36
4

When you get an IConvertable error, that means that you have tried to assign one type to another. In your case, I would imagine that you have tried to assign the textbox to a string. The Textbox is an object. You need to choose the Value out of it and convert that ToString().

For example, if you want to assign your textbox to a string, it would look like this:

myString = Textbox1.Value.ToString();

The IConvertable is the implicit ToString() that you can sometimes use. Not everything has it implemented. In your case, for each control that you are assigning to a string, verify the output will be the string you want. Some will implement the ToString() and it will be just an indicator of the control you are using, not the value you would expect. Look at each item and see where the data you want is stored (Usually in a property called Text or Value). Then verify the data type for that output.

IAmTimCorey
  • 16,412
  • 5
  • 39
  • 75
  • Biggs thanks for your reply. In my msg I have said Textbox. I am sorry its not a textbox but a dropdownlist value which I want to add. – Aditya May 11 '11 at 16:31
1

I wanted to add this because I encountered this error message today, but it was actually just masking a deeper underlying issue.

I was working with some generics and reflection and after digging further the actual error was The type 'Microsoft.SqlServer.Types.SqlGeography' exists in both 'Microsoft.SqlServer.Types.dll' and 'Microsoft.SqlServer.Types.dll'.

The solution was to align the versions of a DLL referenced between my application and a dependency. I did this by installing the specific version from Nuget, and problem solved! If that is not an option, you might be able to use binding redirects, but I have not tried it.

Hope that helps someone else!

jocull
  • 20,008
  • 22
  • 105
  • 149
0

Instead of

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

try doing

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

as ListBox.Items is a collection and you need a specific value not group of values.

Wrong code

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

    }

Do

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

    }

Replace

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

With

 SqlCommand cmd = new SqlCommand(sqlStatement, conn);
FIre Panda
  • 6,537
  • 2
  • 25
  • 38
  • I want to add all the values of the listbox to the database. Secondlly even if I try to use . SelectedItem then I get the following error. 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'. any idea where Iam going wrong – Aditya May 11 '11 at 17:00
  • Thanks for the help you are providing. I am struggling on this for almosta week now. This is what I have done and I am getting an error.....ExecuteNonQuery: CommandText property has not been initialized ...Can you help Please string fileCodeVar = "ListBox2.Items"; string DeptCodeVar = "Dropdownlist1.Text"; foreach (string item in sc) { string sqlStatement = "INSERT INTO FileID(File_Code, Dept_Code) VALUES({0}, {1})"; string.Format(sqlStatement, fileCodeVar, DeptCodeVar); – Aditya May 11 '11 at 17:43
  • Mark it as answer if you find it helpful. – FIre Panda May 11 '11 at 17:51
  • Will definately do that Abdul Bhai but the issue is not resolved. This is what I have done and I am getting an error.....ExecuteNonQuery: CommandText property has not been initialized ...Can you help Please string fileCodeVar = "ListBox2.Items"; string DeptCodeVar = "Dropdownlist1.Text"; foreach (string item in sc) { string sqlStatement = "INSERT INTO FileID(File_Code, Dept_Code) VALUES({0}, {1})"; string.Format(sqlStatement, fileCodeVar, DeptCodeVar); – Aditya May 11 '11 at 17:57
  • The error message that you told me was self explanatory, nevermind, I have updated the answer, hope you get it solved this time. – FIre Panda May 11 '11 at 18:03
  • it says.........Error: The name 'sqlStatement' does not exist in the current context – Aditya May 11 '11 at 18:09
  • You are not supposed to ask such questions my dear, check the updated code now. – FIre Panda May 11 '11 at 18:14
  • :) Please bear with me Abdul Bhai....done what you have said and after all this rigmarole......back to the same error......................Error Message: Object must implement IConvertible. – Aditya May 11 '11 at 18:18
  • What statement on line 75? I should have asked that – FIre Panda May 11 '11 at 18:22
  • Can you suggest an alternate method...I need to save all the items of the listbox and the Dropdownlist value against each of these items to the database – Aditya May 11 '11 at 18:24
  • For each item construct the insert query and get the records inserted. – FIre Panda May 11 '11 at 18:25
  • [InvalidCastException: Object must implement IConvertible.] System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) +9531909 System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType) +5034066 InvalidCastException: Failed to convert parameter value from a ListItemCollection to a String.] System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType) +5033757 System.Data.SqlClient.SqlParameter.GetCoercedValue() +32 System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean isCommandProc) +103 – Aditya May 11 '11 at 18:26
  • Yeah I told you that, in parameter give SelectedItem not Items – FIre Panda May 11 '11 at 18:28
  • Well I am working on a Records Management software - inhouse dev which i am doing myself. I have to generate 100's of unique File ID's each time and the number is not fixed sometime it may be 50 sometime 150 – Aditya May 11 '11 at 18:29
  • Did.......cmd.Parameters["@File_Code"].Value = ListBox2.SelectedItem.Text; Error: Insert Error:The multi-part identifier "ListBox2.Items" could not be bound. The multi-part identifier "Dropdownlist1.Text" could not be bound. – Aditya May 11 '11 at 18:32
  • Pass ListBox2.SelectedItem.Text to the string.Format as there is no @File_Code now. – FIre Panda May 11 '11 at 18:42
  • If i use ListBox2.SelectedItem.ToString; i get a Error Cannot convert method group 'ToString' to non-delegate type 'object'. Did you intend to invoke the method?....Stuck badly on this.....I know its late but thanks a ton for all the help u have given.. I reallly appriciate. – Aditya May 11 '11 at 18:58
  • yeah .ToString(), thats the method come on. – FIre Panda May 11 '11 at 19:02
  • Yes i have done that...can you help me with the tostring code..i am sorry buddy but iam a total novice – Aditya May 11 '11 at 19:20
0

I have been able to resolve the issue based on the advice given by Alexander.

Please find the correct code below.

Thanks for Alexander and all others for their help specially to Abdul who spent a lot of time.

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

}
Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
Aditya
  • 73
  • 9
0

I know this is a bit old, however, I have another solution if anyone is looking for it.

A TIME column in the DB and select query, I received a similar error. For the Model, I was using a string as the time type.

Simply CAST in SQL type TIME or whatever type as VARCHAR(8) or VARCHAR(length-needed).

Jason Foglia
  • 2,414
  • 3
  • 27
  • 48