Usuário com melhor resposta
ÍNDICE FORA DO INTERVALO

Pergunta
-
Olá, estou tentando deletar algumas linhas de um DataGridView, utilizando um laço que o percorre e se ele encontrar valor em branco ou igual a 0 nas células das colunas 4, 5 e 6, ele as deleta.
Parcialmente está funcionando, quando estas condições se encontram na coluna 4, porém, se estas condições estiverem na coluna 5 ou 6, a seguinte exceção é exibida:
Estou utilizando o seguinte código:
try { for (int i = 0; i < dataGridViewInventario.Rows.Count; i++) { while (dataGridViewInventario.Rows[i].Cells[4].Value.ToString() == string.Empty || dataGridViewInventario.Rows[i].Cells[4].Value.ToString() == "0") { dataGridViewInventario.Rows.Remove(dataGridViewInventario.Rows[i]); } while (dataGridViewInventario.Rows[i].Cells[5].Value.ToString() == string.Empty || dataGridViewInventario.Rows[i].Cells[5].Value.ToString() == "0") { dataGridViewInventario.Rows.Remove(dataGridViewInventario.Rows[i]); } while (dataGridViewInventario.Rows[i].Cells[6].Value.ToString() == string.Empty || dataGridViewInventario.Rows[i].Cells[6].Value.ToString() == "0" || dataGridViewInventario.Rows[i].Cells[6].Value.ToString() == "0,00") { dataGridViewInventario.Rows.Remove(dataGridViewInventario.Rows[i]); } } toolStripStatusLabelNumeroTotalItens.Text = dataGridViewInventario.Rows.Count.ToString(); SomarQuantidade(); SomarValorTotal(); } catch (Exception ex) { MessageBox.Show("Advertência: " + ex.ToString(), "Advertência", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
O que posso fazer para que essas condições sejam processadas sem exceção?
- Editado JehanKheller terça-feira, 24 de julho de 2018 18:26
Respostas
-
Olá!
Esta mensagem de erro ocorre porque você já havia removido a linha, e na próxima verificação, tentou remover novamente, mas ela não existia mais. Segue abaixo duas possibilidade que acho que resolverão seu problema:
try { for (int i = 0; i < dataGridViewInventario.Rows.Count; i++) { if (dataGridViewInventario.Rows[i].Cells[4].Value.ToString() == string.Empty || dataGridViewInventario.Rows[i].Cells[4].Value.ToString() == "0") { dataGridViewInventario.Rows.Remove(dataGridViewInventario.Rows[i]); } else if (dataGridViewInventario.Rows[i].Cells[5].Value.ToString() == string.Empty || dataGridViewInventario.Rows[i].Cells[5].Value.ToString() == "0") { dataGridViewInventario.Rows.Remove(dataGridViewInventario.Rows[i]); } else if (dataGridViewInventario.Rows[i].Cells[6].Value.ToString() == string.Empty || dataGridViewInventario.Rows[i].Cells[6].Value.ToString() == "0" || dataGridViewInventario.Rows[i].Cells[6].Value.ToString() == "0,00") { dataGridViewInventario.Rows.Remove(dataGridViewInventario.Rows[i]); } } toolStripStatusLabelNumeroTotalItens.Text = dataGridViewInventario.Rows.Count.ToString(); SomarQuantidade(); SomarValorTotal(); } catch (Exception ex) { MessageBox.Show("Advertência: " + ex.ToString(), "Advertência", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
ou
try { this.dataGridViewInventario.Rows.Cast<DataGridViewRow>() .Where(i => (i.Cells[4].Value.ToString() == string.Empty || i.Cells[4].Value.ToString() == "0") || (i.Cells[5].Value.ToString() == string.Empty || i.Cells[5].Value.ToString() == "0") || (i.Cells[6].Value.ToString() == string.Empty || i.Cells[6].Value.ToString() == "0" || i.Cells[6].Value.ToString() == "0,00")) .ToList().ForEach(i => this.dataGridViewInventario.Rows.Remove(i)); toolStripStatusLabelNumeroTotalItens.Text = dataGridViewInventario.Rows.Count.ToString(); SomarQuantidade(); SomarValorTotal(); } catch (Exception ex) { MessageBox.Show("Advertência: " + ex.ToString(), "Advertência", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
Neste último você deve adicionar a using "using System.Linq;". Espero que te ajude. Bom trabalho!
- Marcado como Resposta JehanKheller sexta-feira, 27 de julho de 2018 11:43
Todas as Respostas
-
Olá!
Esta mensagem de erro ocorre porque você já havia removido a linha, e na próxima verificação, tentou remover novamente, mas ela não existia mais. Segue abaixo duas possibilidade que acho que resolverão seu problema:
try { for (int i = 0; i < dataGridViewInventario.Rows.Count; i++) { if (dataGridViewInventario.Rows[i].Cells[4].Value.ToString() == string.Empty || dataGridViewInventario.Rows[i].Cells[4].Value.ToString() == "0") { dataGridViewInventario.Rows.Remove(dataGridViewInventario.Rows[i]); } else if (dataGridViewInventario.Rows[i].Cells[5].Value.ToString() == string.Empty || dataGridViewInventario.Rows[i].Cells[5].Value.ToString() == "0") { dataGridViewInventario.Rows.Remove(dataGridViewInventario.Rows[i]); } else if (dataGridViewInventario.Rows[i].Cells[6].Value.ToString() == string.Empty || dataGridViewInventario.Rows[i].Cells[6].Value.ToString() == "0" || dataGridViewInventario.Rows[i].Cells[6].Value.ToString() == "0,00") { dataGridViewInventario.Rows.Remove(dataGridViewInventario.Rows[i]); } } toolStripStatusLabelNumeroTotalItens.Text = dataGridViewInventario.Rows.Count.ToString(); SomarQuantidade(); SomarValorTotal(); } catch (Exception ex) { MessageBox.Show("Advertência: " + ex.ToString(), "Advertência", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
ou
try { this.dataGridViewInventario.Rows.Cast<DataGridViewRow>() .Where(i => (i.Cells[4].Value.ToString() == string.Empty || i.Cells[4].Value.ToString() == "0") || (i.Cells[5].Value.ToString() == string.Empty || i.Cells[5].Value.ToString() == "0") || (i.Cells[6].Value.ToString() == string.Empty || i.Cells[6].Value.ToString() == "0" || i.Cells[6].Value.ToString() == "0,00")) .ToList().ForEach(i => this.dataGridViewInventario.Rows.Remove(i)); toolStripStatusLabelNumeroTotalItens.Text = dataGridViewInventario.Rows.Count.ToString(); SomarQuantidade(); SomarValorTotal(); } catch (Exception ex) { MessageBox.Show("Advertência: " + ex.ToString(), "Advertência", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
Neste último você deve adicionar a using "using System.Linq;". Espero que te ajude. Bom trabalho!
- Marcado como Resposta JehanKheller sexta-feira, 27 de julho de 2018 11:43
-
Olá Rodrigo CdS, obrigado por responder. Realmente após algum tempo analisando, entendi que é o que está ocorrendo, pois testando um arquivo em que a primeira condição é atendida, o processo é executado normalmente. Vou testar suas soluções e retorno com um feedback.
-
Olá!
Esta mensagem de erro ocorre porque você já havia removido a linha, e na próxima verificação, tentou remover novamente, mas ela não existia mais. Segue abaixo duas possibilidade que acho que resolverão seu problema:
try { for (int i = 0; i < dataGridViewInventario.Rows.Count; i++) { if (dataGridViewInventario.Rows[i].Cells[4].Value.ToString() == string.Empty || dataGridViewInventario.Rows[i].Cells[4].Value.ToString() == "0") { dataGridViewInventario.Rows.Remove(dataGridViewInventario.Rows[i]); } else if (dataGridViewInventario.Rows[i].Cells[5].Value.ToString() == string.Empty || dataGridViewInventario.Rows[i].Cells[5].Value.ToString() == "0") { dataGridViewInventario.Rows.Remove(dataGridViewInventario.Rows[i]); } else if (dataGridViewInventario.Rows[i].Cells[6].Value.ToString() == string.Empty || dataGridViewInventario.Rows[i].Cells[6].Value.ToString() == "0" || dataGridViewInventario.Rows[i].Cells[6].Value.ToString() == "0,00") { dataGridViewInventario.Rows.Remove(dataGridViewInventario.Rows[i]); } } toolStripStatusLabelNumeroTotalItens.Text = dataGridViewInventario.Rows.Count.ToString(); SomarQuantidade(); SomarValorTotal(); } catch (Exception ex) { MessageBox.Show("Advertência: " + ex.ToString(), "Advertência", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
ou
try { this.dataGridViewInventario.Rows.Cast<DataGridViewRow>() .Where(i => (i.Cells[4].Value.ToString() == string.Empty || i.Cells[4].Value.ToString() == "0") || (i.Cells[5].Value.ToString() == string.Empty || i.Cells[5].Value.ToString() == "0") || (i.Cells[6].Value.ToString() == string.Empty || i.Cells[6].Value.ToString() == "0" || i.Cells[6].Value.ToString() == "0,00")) .ToList().ForEach(i => this.dataGridViewInventario.Rows.Remove(i)); toolStripStatusLabelNumeroTotalItens.Text = dataGridViewInventario.Rows.Count.ToString(); SomarQuantidade(); SomarValorTotal(); } catch (Exception ex) { MessageBox.Show("Advertência: " + ex.ToString(), "Advertência", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
Neste último você deve adicionar a using "using System.Linq;". Espero que te ajude. Bom trabalho!
Acabei de testar a segunda solução e está funcionando perfeitamente. Não cheguei a testar a primeira solução. Muito obrigado pela ajuda e pela atenção.