0
I have a problem with the id variable of my dataGridView, it is giving the following error: "Object reference not defined for an instance of a Visual Studio object". I am using Windows Form, Mysql and Datagridview. Follow the code:
//Declarando variaveis globais
    int id;
    private MySqlConnection cone = new MySqlConnection();
    private MySqlCommand comandoSql = new MySqlCommand();
    private MySqlDataReader dados;
    public frmGerenciarClientes()
    {
        InitializeComponent();
        //Mapeando evento de seleção de celulas da tabela
        //dgvClientes.CellMouseUp += dgvClientes_CellMouseUp;
    }
    private void dgvClientes_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        id = Convert.ToInt32(dgvClientes.Rows[e.RowIndex].Cells["cod_cli"].Value.ToString());
        MySqlCommand cmd = cone.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select * from clientes where cod_cli=" + id + "";
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        MySqlDataAdapter da = new MySqlDataAdapter(cmd);
        da.Fill(dt);
        foreach (DataRow dr in dt.Rows)
        {
            txtIdALT.Text = dr["cod_cli"].ToString();
            txtNome1.Text = dr["nome_cli"].ToString();
            txtEndereco.Text = dr["end_cli"].ToString();
            txtNum.Text = dr["endnum_cli"].ToString();
            txtBairro.Text = dr["bairro_cli"].ToString();
            txtCidade.Text = dr["cid_cli"].ToString();
            mtxtCel.Text = dr["cel_cli"].ToString();
            mtxtTel.Text = dr["tel_cli"].ToString();
            txtEmail.Text = dr["email_cli"].ToString();
        }
    }
Are you sure it’s the
id? This error happens when you try to access a property/method of a null object, but id is an int (have no null).– Genos
Then, the error occurred on the line:
id = Convert.ToInt32(dgvClientes.Rows[e.RowIndex].Cells["cod_cli"].Value.ToString());– Guilherme Lima
Certainly your . Cells["cod_cli"] this NULL, when you try to access your Value will happen this error. what you can do is check with a breakpoint which value you passed on that line.
– Marco Souza