Experts Exchange Solution brought to you by
"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.
Open in new window
Dim src As BindingSource = YourDataGridView.DataSource
We’ve posted a new Expert Spotlight! Joe Anderson (DatabaseMX) has been on Experts Exchange since 2006. Learn more about this database architect, guitar aficionado, and Microsoft MVP.
Private Function GetBoundTableName(dgv As DataGridView) As String
If dgv.DataSource Is Nothing Then Return ""
Dim dt As DataTable = Nothing
If TypeOf dgv.DataSource Is DataTable Then
dt = CType(dgv.DataSource, DataTable)
ElseIf TypeOf dgv.DataSource Is DataSet Then
dt = GetDsDataTable(CType(dgv.DataSource, DataSet), dgv.DataMember)
ElseIf TypeOf dgv.DataSource Is BindingSource Then
dt = GetBsDataTable(CType(dgv.DataSource, BindingSource))
If dt Is Nothing Then Return ""
'Get datatable binded to bindingsource
Private Function GetBsDataTable(ByVal bs As BindingSource) As DataTable
If TypeOf bs.DataSource Is DataTable Then Return CType(bs.DataSource, DataTable)
Return GetDsDataTable(GetBsDataSet(bs), bs.DataMember)
'Get dataset binded to bindingsource
Private Function GetBsDataSet(ByVal bs As BindingSource) As DataSet
If TypeOf bs.DataSource Is DataSet Then Return CType(bs.DataSource, DataSet)
If TypeOf bs.DataSource Is BindingSource Then Return GetBsDataSet(CType(bs.DataSource, BindingSource))
'Get datatable in dataset (either as table or relation)
Private Function GetDsDataTable(ds As DataSet, tableName As String) As DataTable
If ds Is Nothing OrElse tableName = "" Then Return Nothing
If ds.Tables.Contains(tableName) Then Return ds.Tables(tableName)
If ds.Relations.Contains(tableName) Then Return ds.Relations(tableName).ChildTable
Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.
From novice to tech pro — start learning today.
Members can enroll in this course at no extra cost.