Adding a datatable and a session containing datatable - asp.net

I have a session which contains a datatable and also have a function which returns a datatable. I need to add these two. How can I do this?
The below code is to be replaced with correct code.
Session("Table")=Session("Table")+obj.GetCustomer()
...where obj is an object of the business layer.
The '+' sign cannot be used to add these two, so how can I do this?

I would try something like this:
Dim MyDataSet1 As New DataSet()
Dim MyDataSet2 As New DataSet()
Dim dt1 As New DataTable() = ctype(Session("Table"), DataTable)
Dim dt2 As New DataTable() = obj.GetCustomer()
MyDataSet1.Tables.Add(dt1)
MyDataSet2.Tables.Add(dt2)
MyDataSet1.Merge(MyDataSet2)
Session("Table") = MyDataSet1.Tables(0)
Chris

in C#:
Session["Table"] = ((DataSet)Session["Table"]).Merge(obj.GetCustomer());

if the two tables are identical (columns, etc) you might want to go through all rows of one trable and append them to the other one. For convenience you could use an extension method. Maybe there's a more elegant version, but that's a first thought.
-sa

Related

How can I access the rows in a certain column of a DataTable?

I need to populate the rows in specific columns of a DataTable. I have the following setup:
Dim Dt As DataTable = New DataTable()
Dim Da As SqlDataAdapter = New SqlDataAdapter()
Dt.Columns.Add("Column 0")
Dt.Columns.Add("Column 1")
Try
SQLConn.ConOpen()
Da.SelectCommand = SQLcmd_locCodes
Da.Fill(Dt)
SQLConn.ConClose()
Catch ex As Exception
SQLConn.ConClose()
End Try
The SqlDataAdapter is filling the table with data from a database. I need to be able to store the data from the database into specific columns in the DataTable. This is what I'm trying (I'm populating a barchart with the data, but you can ignore that part):
For i As Integer = 0 To Dt.Rows().Count - 1
chart.Series("Series1").Points.AddY(Dt.Rows(i)("Column 0").ToString())
chart.Series("Series1").Points(i).AxisLabel = Dt.Rows(i)("Column 0").ToString()
Next
I know that I'm probably doing some simple task incorrectly. Am I going about accessing the particular rows incorrectly? Any help is appreciated.
You can iterate the rows in the DataTable like this:
For Each dr As DataRow in Dt.Rows
chart.Series("Series1").Points.AddY(dr("Column 0").ToString())
chart.Series("Series1").Points(i).AxisLabel = dr("Column 0").ToString())
Next
However, you are better off removing this:
Dt.Columns.Add("Column 0")
Dt.Columns.Add("Column 1")
Just let the DataAdapter name the columns per the column names specified in the query.
Check out my Question & answer (Bottom of page) from Yesterday
Why I am getting System.Data.DataRowViewā€¯ instead of real values from my Listbox in vb.net
This can be used to extract the information from individual row locations of selected columns.

How to select rows from a DataTable where a Column value is within a List?

Say you had a table in SQL and you wanted to find all the rows where a particular column could be one of 3 options. You could write something like this:
SELECT * FROM MyTable WHERE uid IN (123, 456, 789)
That's effectively what I want to do with a DataTable in VB. I saw this post:
Query rows that the datatable field contain any item in the list<string>
Which seemed to be exactly what I wanted, but it's not working as I expected it to. I basically just used a C# -> VB converter and plugged in my variables and came up with this:
Dim item = From a In dtCodes.AsEnumerable() Where
lstCodes.Any(Function(x) a.Field(Of String)
("Code").ToUpper().Contains(x.ToUpper())) Select a
dtCodes is a DataTable with a column Codes in it. lstCodes is a List(Of String) with some values in it.
item just has all of the rows from dtCodes though, regardless of whether or not their Code column value exists in lstCodes.
What am I missing?
edit; Note that I don't have to use LINQ, if there's an easier or better way.
In the past, I've done this sort of like this:
Dim item = From r as DataRow in dtCodes.Rows
Where lstCodes.contains(r.Item("Codes"))
Select r
Does that work?
The code you have looks ok to me. I tried out this test and it (correctly) prints out
a2
b1
Dim dtCodes As New DataTable
dtCodes.Columns.Add(New DataColumn("Code"))
dtCodes.Rows.Add("a1")
dtCodes.Rows.Add("a2")
dtCodes.Rows.Add("b1")
dtCodes.Rows.Add("b2")
Dim lstCodes As New List(Of String)
lstCodes.Add("b1")
lstCodes.Add("c1")
lstCodes.Add("a2")
Dim item = From a In dtCodes.AsEnumerable()
Where lstCodes.Any(Function(x) a.Field(Of String)("Code").ToUpper().Contains(x.ToUpper()))
Select a
For Each itm In item
Debug.WriteLine(itm("Code").ToString)
Next
Here's a lamba expression that should also work.
Dim item = dtCodes.Select.Where(Function(x As DataRow) lstCodes.Contains(x.Item("Codes")))

Sorting a datatable

I have an asp.net listbox on my page, that I want to sort.
E.g: listbox(lstChooseFields)
MY VB code:
Private Sub LoadColumns()
If drpScreen.SelectedIndex > -1 Then
Dim daLookup As New LookupTableAdapters.LookupTableAdapter
Dim dtLookup As New System.Data.DataTable
dtLookup = daLookup.GetNestedControlValues("EM", "ExcelExport.aspx", "drpScreen", "drpScreen", drpScreen.SelectedValue)
lstChooseFields.DataSource = dtLookup
lstChooseFields.DataValueField = "LKP_ControlValue"
lstChooseFields.DataTextField = "LKP_ControlText"
lstChooseFields.DataBind()
'Dispose
daLookup.Dispose()
End If
End Sub
I have done some searching and found something like 'dtLookup.DefaultView.Sort = "LKP_ControlText" that I can use but it does not work. I don't want to sort in my database only on this page, this listbox (lstChooseFields).
So if you want to sort for the datatable then you have tried dtLookup.DefaultView.Sort = "LKP_ControlText" but you have missed out one piece of word there dtLookup.DefaultView.Sort = "LKP_ControlText asc". This generally works if LKP_ControlText is a column name in the datatable
You must use the word ascthere. which i couldnt find in your question.
After getting the dataTable sorted you can copy the same structure to another datatable if u want by using
Dim dtDuplicateLookup As New DataTable()
dtDuplicateLookup = dtLookup.DefaultView.ToTable(True)
and then access dtDuplicateLookup for further use if you want to retain the previous datatable as it is.
Use the .sorted property for the list box as shown here.
lstChooseFields.Sorted = True
UPDATE: your method was right but just tune it this way. I think you missed the DESC part. The second expression tells it how to sort the dataview.
Dim dataView As New DataView(table)
dataView.Sort = " column_name DESC" //DESC or ASC as per requirement
Dim dataTable AS DataTable = dataView.ToTable()
Else try this. After sorting a defaultview, generally you have to loopback through it
foreach(DataRowView r in table.DefaultView)
{
//... here you get the rows in sorted order
//insert the listbox items one by one here using listbox.add or listbox.insert commands
}

Assigning single dataset column to a combox

I have a dataset that is returned from a web service. The dataset has multiple columns. Is there an easy way to assign a given column to the combobox without having to iterate through the dataset?
Something on the end of this. I have tried all sorts of properties...
ComboBox1.DataSource = suppDataSet.Tables(0)
ComboBox1.DataSource = suppDataSet.Tables(0).Columns(2).tostring
ComboBox1.DataSource = suppDataSet.Tables(0).Columns(2)
thanks for any help.
Use LINQ as follows:
ComboBox1.DataSource = From dr As DataRow In suppDataSet.Tables(0).Rows
Select CStr(dr(column_index or column_name))
Dim oList As New ArrayList
For Each oRow As DataRow In suppDataSet.Tables(0).Rows
oList.Add(oRow.Item(0))
Next
ComboBox1.DataSource = oList
Initially copy required column data in one ArrayList and assign ArrayList to ComboBox1.DataSource.

SqlDataSource.Select()? How do I use this? (ASP.net)

I'm trying to retrieve values using VB.NET from a SQL database. How do I use SqlDataSource.Select()? Is there a way to move the value to a variable that I can use for other things?
I know its kind of scattered and vague but that is the best I can do. I basically need to set a labels text to a value in a table.
This puts the result query in to a DataTable.
DataView view = (DataView)dataSource.Select(new DataSourceSelectArguments());
DataTable groupsTable = view.ToTable();
String value;
foreach (DataRow dr in dt.Rows)
{
// Do something here IE grab the value of the first column
value = dr[0];
}
Repying to last question in comment:
YourTable.Rows(index)(index)
YourTable.Rows(index)("columnname")
I was getting crazy trying to do this simple operation:
retrieving data from sqldatasource and put it into variables that I can manipulate.
At the end, Here the working behind code to do this for VB.NET:
Dim DV As New DataView()
Dim DataTable As New DataTable()
Dim SqlDataSource1 As New SqlDataSource()
Dim VALUE As String
SqlDataSource1.ID = "SqlDataSource1"
Me.Page.Controls.Add(SqlDataSource1)
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Connection_name").ConnectionString
SqlDataSource1.SelectCommand = "SELECT * from Table"
DV = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
DataTable = DV.ToTable()
For Each riga As DataRow In DataTable.Rows
VALUE = riga("table_name").ToString
Next
the for each, in this case gets only the first value but you can get any value from datatable and put it into vector, or other strings, so you can control data coming from sqldatasource.
ENJOY

Resources