System.InvalidCastException:对象必须实现IConvertible

时间:2018-02-07 10:51:30

标签: c# asp.net

我的问题很长,因为它包含大量代码,遗憾的是我无法将其发布得更短。我之前从未收到过这样的错误,这就是我在这里提到帮助的原因。非常感谢您的帮助和时间!

我收到错误" System.InvalidCastException:对象必须实现IConvertible。"

以下是错误消息:

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

我正在使用名为 DatabaseHelper 的I类创建。 我在下面的类的代码(发生错误的地方)中插入了第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();
    }
}


}

另一方面,在 堆栈跟踪 中,它说:

&#34; [InvalidCastException:无法将参数值从Guid转换为String。]&#34;

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!";
        }
    }
} 

请原谅我提出这个问题,感谢所有有几分钟时间帮助我解决问题的人。

1 个答案:

答案 0 :(得分:2)

错误似乎很简单。您添加了参数event_guid,该参数被声明为varchar,但您的c#参数newGUIDGUID而不是字符串。请改用newGUID.ToString(),但您必须对格式化感到满意。如果您想要存储没有-的GUID,请参阅https://msdn.microsoft.com/en-us/library/97af8hh4(v=vs.110).aspx

DatabaseHelper.AddParameter(addEvent, "@event_guid", SqlDbType.VarChar, newGUID.ToString());