I can't for the life of me work out what I am doing wrong here, despite much searching on SO/Google.
Basically I have a simple DataTable which is held in ViewState and adjusted during postbacks. When I try to write out the values, it is just an empty string. Please find below an abbreviated example of what I have - the output in this case just winds up as a string of apostrophes (one for each execution) so it looks as though the rows are being added, but the ("Product") column is empty.
Thanks for your help.
Dim dtItems As New DataTable
If ViewState("Items") Is Nothing Then
Dim dcColumn As DataColumn
dcColumn = New DataColumn()
dcColumn.DataType = Type.GetType("System.String")
dcColumn.ColumnName = "Product"
dtItems.Columns.Add(dcColumn)
ViewState("Items") = dtItems
End If
dtItems = CType(ViewState("Items"), DataTable)
Dim drRow As DataRow
drRow = dtItems.NewRow()
drRow("Product") = "The Product"
dtItems.Rows.Add()
For Each drRow In dtItems.Rows
txtTestDT.Text += drRow(("Product")).ToString & "!"
Next
try replacing:
dtItems.Rows.Add()
with
dtItems.Rows.Add(drRow)
Related
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
}
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
I used to use datasets instead of sqldatareaders and I used to be able to do something like this
If dataset.tables(0).Rows(0)(1).ToString()) = "N" Then
lbl.Text = dataset.tables(0).Rows(0)(2).ToString())
Else
'Do Nothing
End If
This obviously doesn't work with sqldatareaders.
I have code to see if the SQLDatareader has any rows but was wondering if there was a way to get the value of each row
I'm guessing this is possible and i've had a look around but can't seem to find anything
Dim conn As SqlConnection = New SqlConnection("server='h'; user id='w'; password='w'; database='w'; pooling='false'")
conn.Open()
Dim query As New SqlCommand("DECLARE #investor varchar(10), #sql varchar(1000) Select #investor = 69836 select #sql = 'SELECT * FROM OPENQUERY(db,''SELECT * FROM table WHERE investor = ''''' + #investor + ''''''')' EXEC(#sql)", conn)
Dim oDR As SqlDataReader = query.ExecuteReader()
If oDR.HasRows or dataset.tables(0).Rows(0)(1).ToString()) = "N" Then
lbl.Text = dataset.tables(0).Rows(0)(2).ToString())
Else
'Do Nothing
End If
That is the code I have at the moment which obviously doesn't work
Any ideas?
Thanks
When you use the data reader you have to step through each row yourself. Using HasRows is a good start, for it will tell you if the returned result set is empty.
To iterate through the result set you should use the Read() method. It will return true if you are at a row and false when you have moved past the last row.
My Vb is poor so I will give you an example in C# instead:
if (oDR.HasRows && oDR.Read())
{
if (oDR.GetString(0) == "N")
{
lbl.Text = oDr.GetString(1);
}
}
Here I first check that we have a result set with data and then try to move to the first row. If this succeeds I then read the string value of the first column and compare it to "N". If the value is equal to "N" I set the Text property of the lbl variable to the string value of the second column.
This should be equivalent to your algorithm with the dataset. I recommend that you read the MSDN documentation for the SqlDataReader. It is quite good and the example code is useful.
I am new to ASP.NET. I am trying to display my sql results using a list view. I am using the example for grouping my results by a data field from the 4GuysFromRolla.com website. However, I find the way of grouping the items by a data field to be a bit clumsy. Is there a better way to do it?
Thanks.
Nested ListView - http://mattberseth.com/blog/2008/01/building_a_grouping_grid_with.html
I have never used a ListView, but I did do grouping in a GridView. You can try porting this over to a ListView if you want:
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
Dim tblGrid As Table = Me.GridView1.Controls(0)
Dim strLastCat As String = "#"
Dim row As GridViewRow
For Each row In GridView1.Rows
Dim intRealIndex As Integer = tblGrid.Rows.GetRowIndex(row)
Dim strCat As String = Me.GridView1.DataKeys(row.RowIndex).Value
If strLastCat <> strCat Then
Dim rowHeader As New GridViewRow(intRealIndex, intRealIndex, DataControlRowType.Separator, DataControlRowState.Normal)
Dim newCell As New TableCell
newCell.ColumnSpan = Me.GridView1.Columns.Count
newCell.BackColor = System.Drawing.Color.FromArgb(61, 138, 20)
newCell.ForeColor = System.Drawing.Color.FromArgb(255, 255, 255)
newCell.Font.Bold = True
newCell.Font.Size = New FontUnit(FontSize.Larger)
newCell.Text = strCat
rowHeader.Cells.Add(newCell)
tblGrid.Controls.AddAt(intRealIndex, rowHeader)
strLastCat = strCat
End If
Next
MyBase.Render(writer)
End Sub
The code creates headers each category. The final version can be viewed here: http://www.truedietreviews.com/diet-reviews/
I'm looking for an efficient way of searching through a dataset to see if an item exists. I have an arraylist of ~6000 items and I need to determine which of those doesn't exist in the dataset by comparing each item within the arraylist with data in a particular column of the dataset.
I attempted to loop through each item in the dataset for each in the arraylist but that took forever. I then attempted to use the RowFilter method below. None of which looks to be efficient. Any help is greatly appreciated, as you can tell I'm not much of a programmer...
example:
Dim alLDAPUsers As ArrayList
alLDAPUsers = clsLDAP.selectAllStudents
Dim curStu, maxStu As Integer
maxStu = alLDAPUsers.Count
For curStu = 0 To maxStu - 1
Dim DomainUsername As String = ""
DomainUsername = alLDAPUsers.Item(curStu).ToString
Dim filteredView As DataView
filteredView = dsAllStudents.Tables(0).DefaultView
filteredView.RowFilter = ""
filteredView.RowFilter = "szvausr_un = '" & DomainUsername & "'"
Dim returnedrows As Integer = filteredView.Count
If returnedrows = 0 Then
'' Delete the user...
End If
Next
You can get better performance by Sorting the list and ordering the dataset. Then you can walk them together, matching as you go. This is especially true since you are probably already ordering the dataset at least (or, you should be) in the sql query that creates it, making that step essentially free.
You should consider using a generic list rather than an ArrayList, and some other stylistic points on your existing code:
Dim LDAPUsers As List(Of String) = clsLDAP.selectAllStudents
For Each DomainUsername As String in LDAPUsers
Dim filteredView As DataView = dsAllStudents.Tables(0).DefaultView
filteredView.RowFilter = "szvausr_un = '" & DomainUsername & "'"
If filteredView.Count = 0 Then
'' Delete the user...
End If
Next
This does the same thing as your original snippet, but in half the space so it's much cleaner and more readable.
Try switching your array list to Generics. From what I understand they are much faster than an array list.
Here is a previous SO on Generics vs Array List
If you use generics as suggested, you can have two Lists of string and do the following:
for each s as string in LDAPUsers.Except(AllStudents)
''Delete the user (s)
next
Where LDAPUsers and AllStudents are both List(Of String)
Edit:
You can also change the except to:
LDAPUsers.Except(AllStudents, StringComparer.InvariantCultureIgnoreCase)
to ignore case etc.
Edit 2:
To get the generic lists could be as simple as:
Dim LDAPUsers as new List(Of String)(alLDAPUsers.Cast(Of String))
Dim AllStudents as new List(OfString)()
for each dr as DataRow in dsAllStudents.Tables(0).Rows
AllStudents.Add(dr("szvausr_un"))
next
Or you can go with the Linq-y goodness as Joel mentions, but my exposure to that is limited, unfortunately...
Like others have said, generics or linq would be better options. However, I wanted to point out that you don't need to use a DataView. The datatable has a Select method...
dsAllStudents.Tables(0).Select("szvausr_un = '" & DomainUserName & "'")
It returns an array of DataRows. I'm sure it will perform just as poorly as the view but I think it's a little cleaner.
Get the Dim statements out of the loop.... Your performance is suffering from repeated variable instantiation and reallocation.
Also remove any statements you dont need (rowfilter = "")
Dim alLDAPUsers As ArrayList
Dim DomainUsername As String
Dim curStu, maxStu As Integer
Dim filteredView As DataView
Dim returnedrows As Integer
alLDAPUsers = clsLDAP.selectAllStudents
maxStu = alLDAPUsers.Count
For curStu = 0 To maxStu - 1
DomainUsername = alLDAPUsers.Item(curStu).ToString
filteredView = dsAllStudents.Tables(0).DefaultView
filteredView.RowFilter = "szvausr_un = '" & DomainUsername & "'"
returnedrows = filteredView.Count
If returnedrows = 0 Then
'' Delete the user...
End If
Next