Looping through a DataGridView

Experts,

I`m using C# 3.5 VS2008.

I have a populated DatagridView. It does`t  have a DataSource. I populate it programatically.
I want to obtain the column values, and load it to a list.

For a column, I go through each Row and see if the particular cell has a value. If the cell has a value. I add it to the list. (See Code)

The issue is I have a few columns, and I feel its a bad idea to do this for fall. Very clumsy.

Is there a better way to do this. Can I use  LINQ query to a DataGridView. A more elegant and effetient way to do this?

Any help or guidance will be greatly appreciated.


foreach (DataGridViewRow Row in GridView.Rows)
                            {
                                Time += Convert.ToDouble(Row.Cells[0].Value) * FuncPIExt();

                                if (Row.Cells[1].Value != null)
                                {
                                    Locn += Convert.ToDouble(Row.Cells[1].Value) / FuncPIExt();
                                    TimeList.Add(Time);
                                    LocnList.Add(Posn);
                                }
                            }

Open in new window

San24Asked:
Who is Participating?
 
Nathan BoveConnect With a Mentor Software EngineerCommented:
Since you are populating the grid programmatically, you already have access to the underlying data.  Instead of iterating over the grid, simply iterate over the actual data.
0
 
San24Author Commented:
nbove - Cause the edits need to be captured. Lets say I use ObjectA to poulate the gridview, the user can edit the gridview and then ObjectA needs to be updated.
0
 
Nathan BoveConnect With a Mentor Software EngineerCommented:
The most elegant solution would be to use a datasource control.  If you are using objects to drive your data, you have two options.

1)  Use an objectdatasource control
2)  Write your own datasource control

I personally prefer option 2 as it gives me more control over how I want the values to be mapped.  If you are interested in option 1, here is an article about it:
http://msdn.microsoft.com/en-us/library/9a4kyhcx.aspx
0
 
San24Author Commented:
I got a different way fo doing, a bit more elegant than the previous approach. I loop through the rows and then the columns and populate the lists. Works for now.

On a different note. Why does the CurrentCellDirtyStateChanged event get fired twice for a cell edit?

It`s fired when I begin the edit and its fired at the end of the edit. Is there any way to have the event fired only if the value of the cell is changed.

I can`t use CellValueChanged, or Begin Edit or End Edit.
0
 
San24Author Commented:
Different approach taken.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.