Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error : Object must implement IConvertible

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?

like image 540
Aditya Avatar asked Dec 22 '22 14:12

Aditya


2 Answers

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();
}
like image 70
Alexander Avatar answered Jan 04 '23 22:01

Alexander


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.

like image 24
IAmTimCorey Avatar answered Jan 04 '23 23:01

IAmTimCorey