Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a C# Windows App that loads a DataGridView (dataGridView1). I have seven (7) columns, with column 4 being a string (dropdown) and column 7 being a bool. Until a selection is made for column 4, it remains null. What I'm trying to accomplish is that when the bool is checked is column 7, column 4 becomes null.

The code below is my latest attempt; however, with every attempt I've made, I continue getting an "index out of bounds" error.

I'm currently placing this code in CellContentClick.

What I have tried:

foreach(DataGridViewRow row in dataGridView1.Rows)
{
    foreach (DataGridViewCell cell in row.Cells)
    {
        if (row.Cells[7].Value != null)
        {
            row.Cells[4].Value = null;
        }
Posted
Comments
0x01AA 28-Jul-22 13:31pm    
If you have 7 columns, the range to adressing them is 0 upto 6, which in total are the 7 columns. It is called 'zero based' ;)
Member 15154225 28-Jul-22 13:37pm    
Thanks for pointing out such a novice mistake! :) And, to think, I address them as zero through six above in my code. However, now that I've fixed that, if I check any box in column six, it nullifies EVERYTHING in column 3. :\
0x01AA 28-Jul-22 13:46pm    
1. I don't get it what you mean in the last comment.
2. I don't see a reason for foreach (DataGridViewCell cell in row.Cells)
Member 15154225 28-Jul-22 13:52pm    
Sorry, what I meant is that when I started, I knew that the columns were addressed beginning with zero, as I addressed them in a separate piece of code, as such, but mistakenly started at one later on in my code. Thanks for pointing this out.

I'm not sure how to write it without the snippet of code you reference. I've also tried what is shown below, but when I check a single cell in column six, every cell in column three goes null. I'm trying to keep it to the respective row.

for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
if (dataGridView1.Rows[i].Cells[6].Value != null)
{
dataGridView1.Rows[i].Cells[3].Value = null;
}
}
0x01AA 28-Jul-22 14:03pm    
I wrote foreach (DataGridViewCell cell in row.Cells) makes no sense. foreach(DataGridViewRow row in dataGridView1.Rows) is pretty ok.

foreach(DataGridViewRow row in dataGridView1.Rows)
{
  if (row.Cells[6].Value != null)
  {
     row.Cells[3].Value = null;
  }
}

Questionable: You check the boolean column if (row.Cells[6].Value != null). Think about that! If it is != null then it is either true or false which is most probably the value you are looking for ;)

[Edit] I would never use the values of the grid for access the values. I would rather refer to the underlying dataset

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900