简体   繁体   English

System.InvalidCastException:对象必须实现IConvertible

[英]System.InvalidCastException: Object must implement IConvertible

My question is quite long because it consist of a lot of code and unfortunately there is no way for me to post it shorter. 我的问题很长,因为它包含许多代码,但是不幸的是,我没有办法将其缩短。 I have never received such an error before, that is why I'm referring here for help. 我以前从未收到过这样的错误,这就是为什么我要在这里寻求帮助。 Your help and time will be highly appreciated! 您的帮助和时间将不胜感激!

I'm receiving an error "System.InvalidCastException: Object must implement IConvertible." 我收到错误“ System.InvalidCastException:对象必须实现IConvertible。” .

Here is also the error message: 这也是错误消息:

"Line 28: connection.Open(); “第28行:connection.Open();
Line 29: command.Connection = connection; 第29行:command.Connection =连接;
Line 30: return new SqlResult(connection, command.ExecuteReader()); 第30行:返回新的SqlResult(connection,command.ExecuteReader()); Line 31: } 第31行:}
Line 32: catch (SqlException se)" 第32行:catch(SqlException se)”

I'm using class I've created called DatabaseHelper . 我使用的是我创建的名为DatabaseHelper的类 I have inserted comments around Line 30 in the code of the class below (where the error occurs): 我在下面的类的代码中(发生错误的地方)在第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();
    }
}


}

On the other hand in the Stack trace it is saying: 另一方面,在堆栈跟踪中它说:

"[InvalidCastException: Failed to convert parameter value from a Guid to a String.]" “ [InvalidCastException:无法将参数值从Guid转换为字符串。]“

DatabaseHelper.ExecuteQueryWithResult(SqlCommand command) in FOLDERLOCATION\\App_Code\\DatabaseHelper.cs:30 FOLDERLOCATION \\ App_Code \\ DatabaseHelper.cs中的DatabaseHelper.ExecuteQueryWithResult(SqlCommand命令):30

create_event.createEvent_Click(Object sender, EventArgs e) in FOLDERLOCATION\\create_event.aspx.cs:58 FOLDERLOCATION \\ create_event.aspx.cs中的create_event.createEvent_Click(Object sender,EventArgs e):58

Here is the code I've written in create_event.aspx.cs , I've inserted comments arround Line 58 again (where the error occurs): 这是我在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!";
        }
    }
} 

Please excuse me for the long question and thanks to everyone who has couple minutes to spare helping me resolve my issue. 请原谅我的问题很久,感谢所有有几分钟时间来帮助我解决问题的人。

The error seems to be simple. 该错误似乎很简单。 You added the parameter event_guid which is declared to be a varchar but your c# parameter newGUID is a GUID and not a string. 您添加了参数event_guid ,该参数声明为varchar,但您的c#参数newGUIDGUID而不是字符串。 Use newGUID.ToString() instead, but you have to be carfeful about the formatting. 请改用newGUID.ToString() ,但是您必须精通格式。 If you want to store the GUID without - in between please refer to https://msdn.microsoft.com/en-us/library/97af8hh4(v=vs.110).aspx 如果您要存储的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.

相关问题 转换 System.InvalidCastException 时出错:对象必须实现 IConvertible - Error on conversion System.InvalidCastException: Object must implement IConvertible 在类中将属性移动到另一个属性会引发异常“ System.InvalidCastException:&#39;对象必须实现IConvertible。&#39;” - moving property to anther property in class throws exception “System.InvalidCastException: 'Object must implement IConvertible.'”? System.InvalidCastException &quot;对象必须实现 IConvertible。&quot; 使用 BinaryFormatter 反序列化字典时 - System.InvalidCastException "Object must implement IConvertible." when deserializing a Dictionary using a BinaryFormatter Xamarin Forms:尝试为 Android 构建条件格式,错误:System.InvalidCastException Message=Object must implement IConvertible - Xamarin Forms: Trying to build conditional formatting in for Android, Error: System.InvalidCastException Message=Object must implement IConvertible System.InvalidCastException: &#39;无法将&#39;System.Windows.Forms.TextBox&#39;类型的对象转换为&#39;System.IConvertible&#39; - System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Forms.TextBox' to type 'System.IConvertible System.InvalidCastException:“无法将“System.Random”类型的对象转换为“System.IConvertible”类型。” - System.InvalidCastException: "Unable to cast object of type 'System.Random' to type 'System.IConvertible'." System.InvalidCastException: &#39;无法将类型为&#39;System.TimeSpan&#39;的对象转换为类型&#39;System.IConvertible&#39; - System.InvalidCastException: 'Unable to cast object of type 'System.TimeSpan' to type 'System.IConvertible' 在转换为接口时,对象必须实现IConvertible(InvalidCastException) - Object must implement IConvertible (InvalidCastException) while casting to interface 对象到字节— System.InvalidCastException - Object to byte — System.InvalidCastException 对象必须实现IConvertible - Object must implement IConvertible
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM