I am trying to fetch values on a GridView with the following code:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string Username = row.Cells[3].Text;
string Password = row.Cells[4].Text;
string Email = row.Cells[5].Text;
string ID_Inscricao = row.Cells[1].Text;
SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["FormacaoConnectionString"].ToString());
SqlCommand sqlComm = new SqlCommand();
sqlComm = sqlConn.CreateCommand();
sqlComm.Parameters.Add("@Username", SqlDbType.Text);
sqlComm.Parameters.Add("@Password", SqlDbType.Text);
sqlComm.Parameters.Add("@Email", SqlDbType.Text);
sqlComm.Parameters.Add("@ID_Inscricao", SqlDbType.Text);
sqlComm.Parameters["@Username"].Value = Username;
sqlComm.Parameters["@Password"].Value = Password;
sqlComm.Parameters["@Email"].Value = Email;
sqlComm.Parameters["@ID_Inscricao"].Value = ID_Inscricao;
string sql = "INSERT INTO Utilizadores " +
"(Username, Password, Email,ID_Inscricao) " +
"VALUES (@Username, @Password, @Email, @ID_Inscricao)";
sqlComm.CommandText = sql;
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
}
So, the problem is I can’t get the values from the GridView, but instead get a “NullReferenceException was unhandled by user code”. Can anybody tell me what I’m doing wrong?
Best regards
Each line which looks like this:
Requires that parameter to actually exist on the command object, but you’ve commented those lines out. Put back in one of these:
For every parameter you’re setting the value for.
Edited after comment
Based on the fact that this line causes a
NullReferenceException:I can say for cetain that either
a)
rowis null – there is no SelectedRow in your gridb)
row.Cellsis null, the selected row has no cellsc)
row.Cells[3]is null, the selected row has cells, but there is no cell 4(cells is zero based)There is no way of helping you further than that, You should set a breakpoint on the line that is failing and inspect each of the 3 cases above to see which one is null