我想爲每個列表框項目插入列表框項目和一個文本框值到數據庫,當我得到下面的錯誤。錯誤:對象必須實現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'.
任何想法我錯了嗎?
Aditya,你應該添加*評論*的答案,而不是*編輯*他們。我已經拒絕了您的這兩個編輯。 – 2011-05-11 16:52:05