Sorting a datatable - asp.net

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
}

Related

Want to set dropdown list to the first value in a datatable asp.net

I have a drop down list, GroupDropDown, and a data table, GroupDataTable. I have a select statement that only produces one value, i want to set the drop down selected value to the one value in the data table. I've tried a bunch of different stuff and still can't seem to figure it out. Like most errors, I'm sure I am making a silly mistake, but here is my code:
Dim Region As String = Encryption64.Decrypt(Request.QueryString("Region"))
Dim MySqlString As String = "Select GROUPNAME, GROUPOWNERSHIP from Table1 where GROUPNAME like '%" & Region & "%'"
Dim GroupDataTable As DataTable = OleFun.GetMyDataTableString(MySqlString, 2)
GroupDropDown.DataSource = GroupDataTable
GroupDropDown.DataBind()
For Each row As DataRow In GroupDataTable.Rows
Response.Write(row(1))
Next
GroupDropDown.SelectedValue = ?
GetData()
Thanks in advance for your responses
You can select a row and column from a DataTable by name or index and use that value as the SelectedValue
GroupDropDown.SelectedValue = GroupDataTable.Rows[0]["myColumn"].ToString();
//or by column index
GroupDropDown.SelectedValue = GroupDataTable.Rows[0][7].ToString();
VB
GroupDropDown.SelectedValue = GroupDataTable.Rows(0)("myColumn").ToString

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")))

Search data from dataset

I want to search record based on following fields
P_num ,P_name, P_dob,P_code
I am using more than 4 tables to retrive data,
I have created dataset called P_search and i want to fill data into dataset and thsn display it according to which field is selected for search purpose.
Suggest me to write code by creating own function in which all fields and a boolean variable will be taken as parameters
Please help me to write code using VB.net.
I am very new to VB.net. Is ther anyone who can help me giving above code.
Thank You In advance
You use DataTable.Select Method
Private Sub GetRowsByFilter()
Dim table As DataTable = DataSet1.Tables("Orders")
' Presuming the DataTable has a column named Date.
Dim expression As String
expression = "Date > #1/1/00#"
Dim foundRows() As DataRow
' Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression)
Dim i As Integer
' Print column 0 of each returned row.
For i = 0 to foundRows.GetUpperBound(0)
Console.WriteLine(foundRows(i)(0))
Next i
End Sub

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

Adding a datatable and a session containing datatable

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

Resources