0

I am new to C # and have a small problem with DataGridView. I have two codes selected in my database to fill this grid with different columns. I want the user to see only the columns I select, when I start, this works perfectly, but when I try to search the other columns, I get this message: "System.ArgumentOutOfRangeException: 'index was out of range. It must be non-negative and less than the size of the collection 'Arg_ParamName_Name' "

i've tryied to clear the index columns or restart the dataviewgrid, but no success! need help!

  private void ConfiguraDataGridView(int i)
        {
            switch (i)
            {
                case 1:
                    //setando nome do cabeçalho
                    dgAlmoxarifado.Columns[0].HeaderText = "Nome do Item";
                    dgAlmoxarifado.Columns[1].HeaderText = "Cor";
                    dgAlmoxarifado.Columns[2].HeaderText = "Marca";
                    dgAlmoxarifado.Columns[3].HeaderText = "Modelo";
                    dgAlmoxarifado.Columns[4].HeaderText = "Tamanho";
                    dgAlmoxarifado.Columns[5].HeaderText = "Quantidade";
                    dgAlmoxarifado.Columns[6].HeaderText = "Tipo";
                    dgAlmoxarifado.Columns[7].HeaderText = "Quantidade Recomendada";
                    dgAlmoxarifado.Columns[8].HeaderText = "Data de Cadastro";
                    dgAlmoxarifado.Columns[9].HeaderText = "Cadastro";
                    break;

                case 2:
                    //setando nome do cabeçalho
                    dgAlmoxarifado.Columns[0].HeaderText = "Nome do Item";
                    dgAlmoxarifado.Columns[1].HeaderText = "Cor";
                    dgAlmoxarifado.Columns[2].HeaderText = "Marca";
                    dgAlmoxarifado.Columns[3].HeaderText = "Modelo";
                    dgAlmoxarifado.Columns[4].HeaderText = "Tamanho";
                    dgAlmoxarifado.Columns[5].HeaderText = "Quantidade";
                    dgAlmoxarifado.Columns[6].HeaderText = "Tipo";
                    dgAlmoxarifado.Columns[7].HeaderText = "Requisição";
                    dgAlmoxarifado.Columns[8].HeaderText = "Data de Requisição";
                    dgAlmoxarifado.Columns[9].HeaderText = "Quantidade Requisitada";
                    dgAlmoxarifado.Columns[10].HeaderText = "Reposição";
                    dgAlmoxarifado.Columns[11].HeaderText = "Data de Reposição";
                    dgAlmoxarifado.Columns[12].HeaderText = "Quantidade Repositada";
                    dgAlmoxarifado.Columns[13].HeaderText = "Observação";
                    break;
            }
        }


 private void ResetDataGridView()
    {
        // dgAlmoxarifado.CancelEdit();
        // dgAlmoxarifado.Dispose();
        dgAlmoxarifado.Columns.Clear();
        dgAlmoxarifado.Refresh();
        dgAlmoxarifado.DataSource = null;
    }

EDIT: The entire code about this event.

Load Object:

  private void IEstoque_Load(object sender, EventArgs e)
        {              
            ResetDataGridView();
            dgAlmoxarifado.DataSource = mt.CarregarGrid(1, txtSearch.Text);
            ConfiguraDataGridView(1);
        }

Pass to BLL:

  public DataTable CarregarGrid(int opcao, string nomeBusca)
    {
        return cb.CarregarGrid(opcao, nomeBusca);
    }

Pass to DAL:

 public DataTable CarregarGrid(int opcao, string nomeBusca)
        {
            DataTable dt = new DataTable();
            string comando = string.Empty;

            switch (opcao)
            {
                case 1:
                    comando = "select i.nomeItem, i.cor, i.marca, i.modelo, i.tamanho, i.quantidadeDisponivel,i.tipo, i.quantidadeRecomendada, i.cadastradoNoDia, u.nomeUsuario from itens i join movimentacao m on i.id = m.id_itens join usuarios u on u.id = m.id_usuario where i.nomeItem like @nome ";                    

                    break;
                case 2:
                    comando = "select i.nomeItem, i.cor, i.marca, i.modelo, i.tamanho, i.quantidadeDisponivel,i.tipo, m.requisicao, m.dataRequisicao, m.quantidadeRequisitada, m.observacaoRequisicao,m.reposicao, m.dataReposicao, m.quantidadeReposicao, m.observacaoReposicao from itens i join movimentacao m on i.id = m.id_itens join usuarios u on u.id = m.id_usuario where i.nomeItem like @nome ";
                    break;
            }

            MySqlCommand cmd = new MySqlCommand(comando, connection);
            cmd.Parameters.AddWithValue("@nome", "%"+ nomeBusca +"%");

            try
            {
                Conectar();
                MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                da.Fill(dt);
                return dt;
            }
            catch (MySqlException ex)
            {
                string erro = ex.Message;
                return dt;
            }
            finally
            {
                Desconectar();
            }
        }

Then i have this button search:

   private void btnSearch_Click(object sender, EventArgs e)
        {
            if (rdItem.Checked == true)
            {
                ResetDataGridView();
                dgAlmoxarifado.DataSource = mt.CarregarGrid(1, txtSearch.Text);
                ConfiguraDataGridView(1);
            }
            else if (rdMovimentacao.Checked == true)
            {
                ResetDataGridView();
                dgAlmoxarifado.DataSource = mt.CarregarGrid(2, txtSearch.Text);
                ConfiguraDataGridView(2);
            }
        }

When i press that button occurs the error!

  • are you sure that you have the correct datasouce for your headertexts – nbk May 16 '21 at 20:43
  • Hi! Welcome to Stack Overflow! Take a look at [this post](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f), it should be able to answer your question pretty effectively! Make sure to take a look at [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) as well so you can adjust to how we answer questions. – DekuDesu May 16 '21 at 20:43
  • if (e.RowIndex != -1 && e.ColumnIndex != -1){ – H.S May 16 '21 at 20:46
  • nbk Yes, I'm sure. The question is this, when I search for the code it fills the indexes from 0 to 9, then if I search for the other code my index does not start from 0, it starts from 9 and it bursts. – Nicolas Vieira May 16 '21 at 20:51
  • i will post the entire code about this event – Nicolas Vieira May 16 '21 at 21:01
  • i am still not sure how you fill your datagridview o how yot get to have 9 or 12 , rest the dgv and fill it with the ciorrect number of column, you can buit a datatable and add it as datassource, further you can chelcn the number of columns independet of your index and when it is 9 add the mossng coumns, lots and lot of possibilities – nbk May 16 '21 at 21:02
  • I would add a default to the case statement to handle when the case is not 1 or 2. – jdweng May 16 '21 at 21:12
  • @nbk now i post the entire code. – Nicolas Vieira May 16 '21 at 21:20
  • add a halting point at return dt; in CarregarGrid and see what is in the datatable, the seems to be the problem located – nbk May 16 '21 at 21:26
  • @nbk OMG, thanks i had a mysqlcommand problem in the case 2. I'ts Solved! – Nicolas Vieira May 16 '21 at 21:32
  • Now, how can i close this post? or give u like for helping me? – Nicolas Vieira May 16 '21 at 21:40

2 Answers2

0

It worked, thanks to everyone who helped, I had a problem with my select ( an error in the field name) and after following the tip from @Jannick Breunis about cleaning only the datasource and the tip from @Nbk about directly checking the filling of the Data Table was solved.

0

Don't clear the columns, just set the DataSource to null and then set it to the corresponding DataSource.

Jannick Breunis
  • 195
  • 2
  • 14