![](/img/trans.png)
[英]Error on conversion System.InvalidCastException: Object must implement IConvertible
[英]System.InvalidCastException: Object must implement IConvertible
我的問題很長,因為它包含許多代碼,但是不幸的是,我沒有辦法將其縮短。 我以前從未收到過這樣的錯誤,這就是為什么我要在這里尋求幫助。 您的幫助和時間將不勝感激!
我收到錯誤“ System.InvalidCastException:對象必須實現IConvertible。” 。
這也是錯誤消息:
“第28行:connection.Open();
第29行:command.Connection =連接;
第30行:返回新的SqlResult(connection,command.ExecuteReader()); 第31行:}
第32行:catch(SqlException se)”
我使用的是我創建的名為DatabaseHelper的類 。 我在下面的類的代碼中(發生錯誤的地方)在第30行周圍插入了注釋:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
public class DatabaseHelper
{
private static String s_lastError;
private static SqlConnection ConnectDB()
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConStr"].ConnectionString);
return connection;
}
public static SqlResult ExecuteQueryWithResult(SqlCommand command)
{
SqlConnection connection = ConnectDB();
try
{
connection.Open();
command.Connection = connection;
//------error occurs here Line 30-----//
return new SqlResult(connection, command.ExecuteReader());
//--error occurs here Line 30-----//
}
catch (SqlException se)
{
s_lastError = se.Message;
return null;
}
}
public static void ExecuteQueryNoResult(SqlCommand command)
{
SqlConnection connection = ConnectDB();
try
{
connection.Open();
command.Connection = connection;
command.ExecuteNonQuery();
}
catch (SqlException se)
{
s_lastError = se.Message;
}
}
public static void AddParameter(SqlCommand command, String paramName, SqlDbType paramType, Object value)
{
SqlParameter parameter = new SqlParameter(paramName, paramType);
parameter.Value = value;
command.Parameters.Add(parameter);
}
public static String GetLastError()
{
return s_lastError;
}
public class SqlResult
{
private SqlDataReader m_reader;
private SqlConnection m_connection;
public SqlResult(SqlConnection connection, SqlDataReader reader)
{
m_connection = connection;
m_reader = reader;
}
public bool HasResults()
{
return m_reader.HasRows;
}
public SqlDataReader GetReader()
{
return m_reader;
}
public Dictionary<string, object> GetNextRow()
{
if (m_reader != null && m_reader.Read())
{
Dictionary<string, object> result = new Dictionary<string, object>();
for (int i = 0; i < m_reader.FieldCount; i++)
{
result.Add(m_reader.GetName(i), m_reader.GetValue(i));
}
return result;
}
return null;
}
public void Close()
{
m_reader.Close();
m_connection.Close();
}
}
}
另一方面,在堆棧跟蹤中它說:
“ [InvalidCastException:無法將參數值從Guid轉換為字符串。]“
FOLDERLOCATION \\ App_Code \\ DatabaseHelper.cs中的DatabaseHelper.ExecuteQueryWithResult(SqlCommand命令):30
FOLDERLOCATION \\ create_event.aspx.cs中的create_event.createEvent_Click(Object sender,EventArgs e):58
這是我在create_event.aspx.cs中編寫的代碼,我再次在第58行周圍插入了注釋(發生錯誤的地方):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Net.Mail;
using System.Collections;
using System.Data;
public partial class create_event : System.Web.UI.Page
{
private int UserID = -1;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["New"] != null)
{
Page.Visible = true;
UserID = Convert.ToInt32(Session["userid"]);
}
else
{
Response.Write("<script language='javascript'>window.alert('To create an event please Login!');window.location='Login.aspx';</script>");
}
}
String newGUID = Guid.NewGuid().ToString();
protected void createEvent_Click(object sender, EventArgs e)
{
if (TextBox_eventName.Text.Length > 0 && TextBox_eventLocation.Text.Length > 0)
{
Guid newGUID = Guid.NewGuid();
int eventID = -1;
SqlCommand addEvent = new SqlCommand("spAddEvent");
addEvent.CommandType = CommandType.StoredProcedure;
addEvent.CommandText = "spAddEvent";
DatabaseHelper.AddParameter(addEvent, "@event_guid", SqlDbType.VarChar, newGUID);
DatabaseHelper.AddParameter(addEvent, "@event_name", SqlDbType.VarChar, TextBox_eventName.Text);
DatabaseHelper.AddParameter(addEvent, "@event_location", SqlDbType.VarChar, TextBox_eventLocation.Text);
DatabaseHelper.AddParameter(addEvent, "@event_description", SqlDbType.Text, TextBox_Description.Text);
DatabaseHelper.AddParameter(addEvent, "@start_time", SqlDbType.DateTime, TextBox_eventSTime.Text);
DatabaseHelper.AddParameter(addEvent, "@end_time", SqlDbType.DateTime, TextBox_eventETime.Text);
DatabaseHelper.AddParameter(addEvent, "@event_type", SqlDbType.VarChar, DropDownListEventType.Text);
DatabaseHelper.AddParameter(addEvent, "@organizer", SqlDbType.Int, UserID);
//------------Line 58 error occurs here--------//
DatabaseHelper.SqlResult added = DatabaseHelper.ExecuteQueryWithResult(addEvent);
//------------Line 58 error occurs here---------//
if (added.HasResults())
{
Dictionary<string, object> eventInfo = added.GetNextRow();
eventID = Convert.ToInt32(eventInfo[""]);
int user_id = -1;
SqlCommand checkUser = new SqlCommand("SELECT user_id FROM Users WHERE email = @email");
DatabaseHelper.AddParameter(checkUser, "@email", SqlDbType.VarChar, TextBox_inviteGuest.Text);
DatabaseHelper.SqlResult userResult = DatabaseHelper.ExecuteQueryWithResult(checkUser);
if (!userResult.HasResults())
{
userResult.Close();
SqlCommand AddUser = new SqlCommand("spAddUsers");
AddUser.CommandType = CommandType.StoredProcedure;
AddUser.CommandText = "spAddUsers";
DatabaseHelper.AddParameter(AddUser, "@email", SqlDbType.VarChar, TextBox_inviteGuest.Text);
DatabaseHelper.SqlResult insertS = DatabaseHelper.ExecuteQueryWithResult(AddUser);
if (insertS.HasResults())
{
user_id = Convert.ToInt32(insertS.GetNextRow()[""]);
}
}
else
{
Dictionary<string, object> result = userResult.GetNextRow();
user_id = Convert.ToInt32(result["user_id"]);
}
userResult.Close();
SqlCommand checkUserEvent = new SqlCommand("spCheckUserEvent");
checkUserEvent.CommandType = CommandType.StoredProcedure;
checkUserEvent.CommandText = "spCheckUserEvent";
DatabaseHelper.AddParameter(checkUserEvent, "@user_id", SqlDbType.Int, user_id);
DatabaseHelper.AddParameter(checkUserEvent, "@event_id", SqlDbType.Int, eventID);
DatabaseHelper.AddParameter(checkUserEvent, "@role", SqlDbType.VarChar, Status.guest);
DatabaseHelper.AddParameter(checkUserEvent, "@status", SqlDbType.VarChar, Status.awaitingAnswer);
DatabaseHelper.ExecuteQueryNoResult(checkUserEvent);
{
const string username = "XXXX";
const string password = "XXXX";
SmtpClient smtpclient = new SmtpClient();
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
MailAddress fromaddress = new MailAddress("XXXX");
smtpclient.Host = "smtp.gmail.com";
smtpclient.Port = 587;
mail.From = fromaddress;
mail.To.Add(TextBox_inviteGuest.Text);
mail.Subject = ("Invitation for an event: " + TextBox_eventName.Text);
mail.IsBodyHtml = true;
string eventLink = "http://localhost:61638/NewEvent.aspx?" + "Guid=" + newGUID + "&" + "email=" + TextBox_inviteGuest.Text;
string eLink = "<a href=\"" + eventLink + "\">" + eventLink + "</a>";
mail.Body = "Hello," + "<br /><br />" +
"You have been invited to <b>'" + TextBox_eventName.Text + "'</b><br /><br />" +
"Please click the link below to let the organizer know if you can make it, see the details and leave a comment. <br />" + eLink + "<br /><br />" +
"Best regards, " + "<br />" + "The team of XXX.";
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
try
{
smtpclient.Send(mail);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
Response.Redirect("NewEvent.aspx?guid=" + newGUID);
}
else
{
LabelError.Text = "You haven't inserted Event name and Event location!";
}
}
}
請原諒我的問題很久,感謝所有有幾分鍾時間來幫助我解決問題的人。
該錯誤似乎很簡單。 您添加了參數event_guid
,該參數聲明為varchar,但您的c#參數newGUID
是GUID
而不是字符串。 請改用newGUID.ToString()
,但是您必須精通格式。 如果您要存儲的GUID不帶-
,請參閱https://msdn.microsoft.com/en-us/library/97af8hh4(v=vs.110).aspx
DatabaseHelper.AddParameter(addEvent, "@event_guid", SqlDbType.VarChar, newGUID.ToString());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.