Retrieve list of all DatagridViews

phudgens

Member
Joined
Nov 19, 2013
Messages
19
Programming Experience
10+
I am using C# in VS Express 2013 and have created a multi-tab form with multiple DataGridViews on different tabs. Is there a way to generate a list of the names of my DataGridViews during runtime (ie, DataGridView2, DataGridView4, etc)? Have tried several things thus far with no success - nor can I find anything on the web.
Thanks,
Paul Hudgens
Denver
 
This code will work regardless of the number of DataGridViews on each TabControl:
var gridNames = this.tabControl1.TabPages
                                .Cast<TabPage>()
                                .SelectMany(tp => tp.Controls.OfType<DataGridView>()
                                                             .Select(dgv => dgv.Name));

MessageBox.Show(string.Join(", ", gridNames));
That first line, which might look a bit complex, is using LINQ, which makes database-like queries like this much easier. The SelectMany function takes each item in a collection and selects something from it, then combines all resultant lists into a single list. In this case, the collection is the TabPages in the TabControl and what it selects is the name of each control of type DataGridView on the TabPage.

Having said that, is it really the names of the grids you want? What use are the names really, other than as a means to get the grids themselves by name? Surely it;s actually the grids themselves you are interested in. You have to have the grids to get the names though, so why get the grids to get the names, only to use those names to get the grids?
 
Last edited:
I have 5 DGVs in my project - each with multiple columns and multiple possible rows. I have written code to facilitate the loading of DGV data from an external file - which the user has the option of creating from within the program. Rather than having to refer to each DGV individually, I assumed that there would be a way to create a list internally from which I could then create a dictionary of all DataGridViewColumns for all DGVs in the entire project. From there it would be relatively easy to output/input data to/from the external file. There is a problem however, in that the DGV name in gridNames is stored as a string, rather than as a DataGridView. Is there a way to convert the string form of the DGV name to a DataGridView so that it could be used in something like:
foreach (DataGridViewColumn DGVColumn in ThisDGV.Columns)?

Thanks,
Paul Hudgens
Denver
 
Back
Top Bottom