简体   繁体   中英

An exception of type 'System.InvalidOperationException' occurred in System.Data.dll that inserting data into Gridview

I try to read session varible Id on myconferences page and fill the Gridview with my query but I got error that 'System.InvalidOperationException' from cmd.ExecuteNonQuery() . How to fix it?
在此处输入图片说明


My codes

 public partial class MyConferences : System.Web.UI.Page
{
    internal User user;

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            BindGrid();

        }
    }

    private void BindGrid()
    {
        object user = Session["Id"];

        if(user != null)
        {
            user = Session["user"] as User;
        }

        string constr = ConfigurationManager.ConnectionStrings[0].ConnectionString;
        using(SqlConnection con = new SqlConnection(constr))
        {
            string query = "select Conferences.conferenceName , Conferences.conferencePlace , Conferences.conferenceDate , Conferences.category from Conferences inner join Users on Conferences.fk_Users = Users.Id where Users.Id =@Id";

            using(SqlCommand cmd = new SqlCommand(query))
            {

                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Id", ((object)user) ?? DBNull.Value);
                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();                    
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
}

Also User object on Login page.

  User u = new User();
                u.UserId = Convert.ToInt32(dr["Id"]);
                u.Name = dr["name"] != DBNull.Value ? dr["name"].ToString() : string.Empty;
                u.Surname = dr["surname"] != DBNull.Value ? dr["surname"].ToString() : string.Empty;
                u.Email = dr["email"] != DBNull.Value ? dr["email"].ToString() : string.Empty;
                Session["user"] = u;

However I couldn't get the actual exception detail in Additional Information because it is not in English language but what mistakes I can see directly are below

First mistake,

You are calling cmd.ExecuteNonQuery() after con.Close(); so it cannot execute the command since connection is no more open.

Second mistake,

ExecuteNonQuery() is used for insert/update queries. It will trow error since the query is returning result set which can be caught using methods like ExecuteReader but not by method ExecuteNonQuery

Actually I am not getting why you are calling it in the first place since you have already loaded data using cmd.ExecuteReader(); .

How to fix it

Remove this line

cmd.ExecuteNonQuery();

And correct this line, (this is not the clean way to do it but I am writing it as per your current code)

cmd.Parameters.AddWithValue("@Id", ((object)user) == null?(object)DBNull.Value:(object)((object)user).UserId);

Edit

The full code

private void BindGrid()
{
    object id = Session["Id"];

    if(id != null)
    {
        user = Session["user"] as User;
    }

    string constr = ConfigurationManager.ConnectionStrings[0].ConnectionString;
    using(SqlConnection con = new SqlConnection(constr))
    {
        string query = "select Conferences.conferenceName , Conferences.conferencePlace , Conferences.conferenceDate , Conferences.category from Conferences inner join Users on Conferences.fk_Users = Users.Id where Users.Id =@Id";

        using(SqlCommand cmd = new SqlCommand(query))
        {

            cmd.Connection = con;
            cmd.Parameters.AddWithValue("@Id", user == null ? (object)DBNull.Value : (object)user.UserId);
            con.Open();
            GridView1.DataSource = cmd.ExecuteReader();
            GridView1.DataBind();                    
            con.Close();
        }
    }
}

You're trying to pass an object to the Users.Id field (which I assume is an int)

Try

cmd.Parameters.AddWithValue("@Id", (int)user.UserId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM