What is the easiest way to retrieve the text value of a cell in a datagrid? I have search for a while and don't see anything out there. Thanks for any help.
Printable View
What is the easiest way to retrieve the text value of a cell in a datagrid? I have search for a while and don't see anything out there. Thanks for any help.
Something like this:
DirectCast(Datagrid1.DataSource,Dataset).tables(0).Rows(0).Item(0).tostring
strName = DirectCast(dgResume.DataSource,DataSet).Tables(0).Rows(intRow).Item(0).ToString()
here is what that line looks like. strName is definded as a string variable. When I run it, I get the System.InvalidCastException: Specified cast is not valid.
Does anyone know why I am getting this error? Thanks for any help
Ok I figured it out. Rather then DirectCast from datagrid to dataset, I just directly refer to the dataset the populated the datagrid.
I usually just loop through the values of the dataset..
This iterates through all rows and columns of the dataset..... MyDataSet would be a dataset declared = to the datasource of your datagridVB Code:
Dim MyDataSet As New System.Data.DataSet 'you can just replace this with your current dataset MyDataSet = DataGrid1.DataSource 'replace with current dataset For Each MyRow As System.Data.DataRow In MyDataSet.Tables(0).Rows Dim Mystring As String For Each MyColumn As System.Data.DataColumn In MyDataSet.Tables(0).Columns Mystring = MyDataSet.Tables(0).Rows(I).Item(MyColumn) Next msgbox(Mystring) I = I + 1 Next
Have you bound the DataGrid to a DataSet or a DataTable? Also note that the data in the grid does not always correspond to the data in the underlying table, because the displayed data actually corresponds to a DataView, which can be filtered and/or sorted. If you've bound the grid to a DataSet then I suggest this code:If it is in fact bound to a DataTable then you would use something like this:VB Code:
Dim myString As String = DirectCast(myDataGrid.DataSource, DataSet).Tables(myDataGrid.DisplayMember).DefaultView(rowIndex)(columnNameOrIndex).ToString()VB Code:
Dim myString As String = DirectCast(myDataGrid.DataSource, DataTable).DefaultView(rowIndex)(columnNameOrIndex).ToString()