Sunday 10 June 2018

How to empty the cells of a DataGridView in C#?




I've found questions similar on SO already, all over the net actually. Though I haven't found a working answer yet.



So I'm working in a windows form application using Visual studio 2008. Language is C#



I have a DataGridView that is not bound to a DataSource.



so:



MyDataGridView.DataSource = null;



wont work...



I've also tried



MyDataGridView.Rows.Clear();


But this removes all my custom made rows.




So I'm now looking for a way to just empty the contents of all cells (not including header cells). So it shouldn't affect anything else but the contents of the cells itself.


Answer



I just figured out how to do it myself, I simply loop trough the table, clearing every cell I encounter.



note: "dgUsers" is the name of my DataGridView



for (int i = 0; i < dgUsers.Columns.Count ;i++ )
{
for (int j = 0; j < dgUsers.Rows.Count; j++)
{

dgUsers.Rows[j].Cells[i].Value = "";
}
}


I bet there is a better way to do this and this might look a bit sloppy but it does the job. Yet I'd like to hear a better solution that clears the data.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...