Question Reference a previously created datatable by entering a string?

smiley_mick

New member
Joined
Mar 22, 2011
Messages
2
Programming Experience
Beginner
I want a quick way to be able to see all of the data that is currently in a DataTable.
I want to be able to reference the name of the DataTable by entering string into a TextBox, have my program recognise that it's a DataTable that has data in it, and display that data in a DataGridView.
Maybe this isn't the best approach but it's better than creating a Select Case scenario for each datatable I've created.
Any ideas?
 
Put all your DataTables in a DataSet and set their TableName property. You can then get that DataTable by indexing the DataSet's Tables collection by name. The best option is to create, name and populate the DataTable in one line of code, e.g.
VB.NET:
myDataAdapter.Fill(myDataSet, "TableName")
That will create a DataTable with a TableName of "TableName" and add it to myDataSet's Tables collection.

Rather than having the user enter a table name in a TextBox, why not use a ComboBox? You already know what the names are so you can provide the list. That way they can't make a mistake and you don't have to check that the table exists. In fact, if you populate it using a LINQ query, you can make getting the DataTable itself even easier, e.g.
VB.NET:
With myComboBox
    .DisplayMember = "Name"
    .ValueMember = "Table"
    .DataSource = (From t In myDataSet.Tables.Cast(Of DataTable)() _
                   Order By t.TableName _
                   Select New With {.Name = t.TableName, .Table = t}).ToArray()
End With
The user will see an alphabetised list of table names and, when they make a selection, you get the DataTable from the ComboBox's SelectedValue property, e.g.
VB.NET:
With myDataGridView
    .DataSource = Nothing
    .Columns.Clear()
    .DataSource = myComboBox.SelectedValue
End With
 
Back
Top