Object reference not set to an instance of a Visual Studio object

0

I am having problem in the id variable of my dataGridView, it is giving the following error: "Object reference not set to an instance of a Visual Studio object". I am using Windows Form, MySQL and the DataGridView. Here is 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();

        }
    }
    
asked by anonymous 04.11.2016 / 11:53

1 answer

1

As discussed, this error occurs when trying to access a property / method of a null object. How the exception is occurring on the line

id = Convert.ToInt32(dgvClientes.Rows[e.RowIndex].Cells["cod_cli"‌​].Value.ToString());

Check which of the components of this expression is null:

  • See if dgvClientes is null; Otherwise
  • See if the expression dgvClientes.Rows[e.RowIndex] returns null; Otherwise
  • See if the expression dgvClientes.Rows[e.RowIndex].Cells["cod_cli"‌​] returns null. Otherwise
  • See if the expression dgvClientes.Rows[e.RowIndex].Cells["cod_cli"‌​].Value returns null.

If it's none of them then we still have not found the real problem.

    
04.11.2016 / 12:11