Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Iam making a dynamic count in datagridview, i've done this in the followed ways. yet i can't solve it, perhaps someone else will know how to do my execution right.

i want it to do the followed;

the columns have to be counted (as rows) e.x. there are 30 columns you need to count from 0 to 30 and check each column 1by1, now the datatable is disposed on the load procedure so we can't get values from the datatable anymore, just the datagridview which is populated.

if somehow i could solve the cells[f] (count the cells from 0 to 30) than it would be solved but apperently somehow i cannot.

its hard to explain but i'd hope you will understand it.

C#
int columnz = datatable.columns.count;
columns.Text = columnz.ToString();


C#
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
    for (int f = 0; i <= Convert.ToInt64(columns.Text); i++)
    {
        if (dataGridView1.Rows[i].Cells[f].Value.ToString() == null)
        {
            dataGridView1.Rows.RemoveAt(i);
            i--;
        }
    }
}


i've also tried to do Cells(f.tostring())... i dont know what to do anymore.
Posted
Comments
Animesh Datta 21-May-14 5:32am    
In your second loop you are not checking the column one by one . change the loop like this way

for (int f = 0; f <= Convert.ToInt64(columns.Text); f++)

and let me know
misterd1 21-May-14 5:58am    
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

(falls out of value index? may not be negative or is incorrect)
Animesh Datta 21-May-14 6:09am    
where the error occured ?
misterd1 21-May-14 6:48am    
Additional information: The index is out of range. These must not be negative and must be less than the size of the collection.
Animesh Datta 21-May-14 7:01am    
This error comes when datagridview has no rows or no cells and you want to compare its cell with another value .

1 solution

try below code
C#
for (int row = 0; row < dataGridView1.Rows.Count; ++row) {
    bool isEmpty = false;
    for (int col = 0; col < dataGridView1.Columns.Count; ++col) {
        object value = dataGridView1.Rows[row].Cells[col].Value;
        if (value  == null || value  == DBNull.Value || String.IsNullOrWhitespace(value .ToString()) {
            isEmpty = true;
            break;
        }
    }
    if (isEmpty) {
        dataGridView1.Rows.RemoveAt(row--);
    }
}
 
Share this answer
 
Comments
misterd1 21-May-14 7:09am    
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

Additional information: Can not delete unallocated new row.

on the test attempt

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