I am attempting to update my rows through session in GridView. Only the Row update operation in GridView throws server error. Other operations in my project works fine. When I add this following code to update the index, it throws server error. Please guide.
Server Error -
Server Error in '/' Application.
Unable to cast object of type 'System.String' to type 'System.Data.DataTable'.
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: Unable to cast object of type 'System.String' to type 'System.Data.DataTable'.
Source Error:
Line 107: con.Open();
Line 108:
Line 109: DataTable dt = (DataTable)Session["name"];
Line 110:
Line 111: //Update the values.
My aspx.cs code to update rows in gridview:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
DataTable dt = (DataTable)Session["name"];
//Update the values.
GridViewRow row = GridView1.Rows[e.RowIndex];
//int id = Convert.ToInt32(Label.[e.RowIndex].Values["id"].ToString());
dt.Rows[row.DataItemIndex]["name"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["role"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["gender"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["exp"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["join"] = ((TextBox)(row.Cells[5].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["report"] = ((TextBox)(row.Cells[6].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["email"] = ((TextBox)(row.Cells[7].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["mobile"] = ((TextBox)(row.Cells[8].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["birth"] = ((TextBox)(row.Cells[9].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["address"] = ((TextBox)(row.Cells[10].Controls[0])).Text;
SqlCommand com = new SqlCommand("update_employee", con);
com.CommandType = CommandType.StoredProcedure;
com.Connection = con;
com.Parameters.Add("@id", SqlDbType.Int).Value = id;
com.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = name;
com.Parameters.Add("@address", SqlDbType.VarChar, 50).Value = address;
com.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = email;
com.Parameters.Add("@mobile", SqlDbType.VarChar, 50).Value = mobile;
com.Parameters.Add("@gender", SqlDbType.VarChar, 50).Value = gender;
com.Parameters.Add("@role", SqlDbType.VarChar, 50).Value = role;
com.Parameters.Add("@birth", SqlDbType.VarChar, 50).Value = birth;
com.Parameters.Add("@join", SqlDbType.VarChar, 50).Value = join;
com.Parameters.Add("@exp", SqlDbType.VarChar, 50).Value = exp;
com.Parameters.Add("@report", SqlDbType.VarChar, 50).Value = report;
com.ExecuteNonQuery();
com.Dispose();
con.Close();
GridView1.EditIndex = -1;
bindgrid();
}