Error: object must implement IConvertible

I am trying to insert list items and the text box value for each list item into the database when I get the following error.

IF I try to insert list items only I succeed, but when I try to insert the value of a text field, I get this error. Could you 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 list values โ€‹โ€‹to the database.

Secondly, 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'm wrong?

+3
source share
5 answers

if your list contains only string elements, you need to change the next line

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

to

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

if the elements are complex objects, add .ToString () to the end

UPD: if you want to add all the ListBox items, you need to skip its collection of items and execute the query to query the query, for example:

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

IConvertable, , . , , . - . ToString().

, , :

myString = Textbox1.Value.ToString();

IConvertable - ToString(), . . , , , . ToString(), , , . , , ( Text Value). .

+2

, .

, .

, .

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

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

    }

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

    }

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

 SqlCommand cmd = new SqlCommand(sqlStatement, conn);
0

All Articles