|
Question : Getting item from DataTable based on column index
|
|
Dear Experts,
I am having a problem with a DataTable.
I'm trying to loop through each row in a datatable as follows and retrieve a value from a particular column. I know the column index only.
Here's my attempt, but dr.Table.Columns(_ColumnIndex_Name.SelectedValue doesn't return anything...
Dim dr As DataRow For Each dr In FullImportSet().Tables(0).Rows
dsXfer.Tables(0).Rows.Add(dr.Table.Columns(_ColumnIndex_Name.SelectedValue).ToString, "Outlet_Name")
'DoSingleImport()
Next
Does anybody have any suggestions?
Thanks
Nick
|
|
Answer : Getting item from DataTable based on column index
|
|
What is _ColumnIndex_Name? The context makes it look like it is a listbox or combobox which has its DataSource set to XferImportSet.Tables(0), its DisplayMember set to one field/column in that DataTable and its DisplayMember set to another field/column in the DataTable. If so - while ZeonFlash's suggestion might well solve your problem - I wonder why you are binding to a String datatype column when you are expecting to read an Integer value from it? Still, I suppose, that may be necessary.
But if that is the answer or not, with code like this it might be worth you using "helper" variables. The point here is that every time this line is hit
dsXfer.Tables(0).Rows.Add(dr.Table.Columns(_ColumnIndex_Name.SelectedValue).ToString, "Outlet_Name")
you're giving the processor a lot of unnecessary work to do. It has to look up, with reference to dr, what the relevant datatable is and it then has to look up, within that datatable, which column is referenced by (_ColumnIndex_Name.SelectedValue) or by CInt(_ColumnIndex_Name.SelectedValue). But neither of those values are going to change within the loop
For Each dr In FullImportSet().Tables(0).Rows '[...] Next
On every pass the datatable is going to be FullImportSet().Tables(0) because, by definition, that is where Each dr comes from. And the Column index is always going to be _ColumnIndex_Name.SelectedValue because, while in the loop, the processor is fully occupied so that no new selection can be made.
So how about
Dim dt As DataTable = FullImportSet().Tables(0) Dim colIndex As Integer = _ColumnIndex_Name.SelectedValue ' or CInt(_ColumnIndex_Name.SelectedValue) Dim dr As DataRow For Each dr In dt.Rows dsXfer.Tables(0).Rows.Add(dr.Item(colIndex).ToString, "Outlet_Name") Next
Roger
|
|
|
|