SqlDataSource.Select()? How do I use this? (ASP.net) - 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

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

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
}

Find nested gridview in user defined function

I'm having a problem populating a child gridview using a function I define. I keep getting the error "Object reference not set to an instance of an object". What am I doing wrong? Am I using the FindControl function incorrectly? It doesn't seem to find the child gridview.
Sub RecordsByZip()
Dim DBConn As New SqlConnection(Application("DBConn"))
Dim gv1 As GridView
gv1 = grdTotal
Dim gv2 As GridView
gv2 = DirectCast(gv1.FindControl("grdChild"), GridView)
Dim ZipCode = lbZip.SelectedItem
For Each ZipCode In lbZip.Items
If ZipCode.Selected = True Then
Dim cmdZip As SqlCommand = New SqlCommand("spPICAInsertTotals2", DBConn)
cmdZip.CommandType = CommandType.StoredProcedure
strZip = ZipCode.Text
strUser = Session("User")
Dim Zip As New SqlParameter("#Zip", SqlDbType.VarChar)
Zip.Value = strZip
cmdZip.Parameters.Add(Zip)
Dim UserID As New SqlParameter("#UserID", SqlDbType.Int)
UserID.Value = strUser
cmdZip.Parameters.Add(UserID)
DBConn.Open()
gv1.DataSource = cmdZip.ExecuteReader
gv1.DataBind()
gv1.Visible = True
DBConn.Close()
End If
Next
btnExport.Visible = True
lblmsg.Visible = False
' Dim DBConn = New SqlConnection(Application("DBConn"))
Dim cmdCounty As SqlCommand = New SqlCommand("spPICAInsertTotals", DBConn)
cmdCounty.CommandType = CommandType.StoredProcedure
'Dim gv As GridView = TryCast(e.Row.FindControl("grdChild"), GridView)
strUser = Session("User")
Dim UserID2 As New SqlParameter("#UserID", SqlDbType.Int)
UserID2.Value = strUser
cmdCounty.Parameters.Add(UserID2)
DBConn.Open()
gv2.DataSource = cmdCounty.ExecuteReader
gv2.DataBind()
gv2.Visible = True
DBConn.Close()
btnExport.Visible = True
lblmsg.Visible = False
lblInstructions.Visible = False
End Sub
First of all . . .
Just as a disclaimer, I normally use repeater controls instead of gridview controls.
But this may help you . . .
I can tell you that with repeater controls, if you want to find a nested repeater then you must look for them inside the item of the parent repeater to which they belong. Essentially, what you are trying to do with the code above, is find grdChild when there might actually be several grdChild (it is a nested gridview, after all). I'd be willing to bet this is where you're object reference error is occurring.
In other words, if you want to find the nested repeater with the ID nestedRepeater, and you know it is located in the first item of your main repeater (which in this case I've assigned to the myRepeater variable), you can do this:
Dim myItem as RepeaterItem = myRepeater.Items(0)
Dim Rep2 as Repeater = myItem.FindControl("nestedRepeater")
Using SqlDataAdapter and a DataSet (recommended)
Dim sa As New SqlDataAdapter(cmdCounty) 'Initialize the SqlDataAdapter and assign the SqlCommand object to it.
Dim ds As New DataSet() 'Initialize the DataSet (we will bind this to the gridview)
Try 'The Try/Catch statements help you to handle errors.
cmdCounty.Connection.Open() 'Open the connection to the database.
sa.Fill(ds) 'This statement uses the SqlDataAdapter to easily execute the SqlCommand (using the query specified in the SqlCommand object) and . . .
'. . .use that data to fill our dataset.
cmdCounty.Connection.Close() 'These statement close the connection and dispose of the SqlCommand object. Note: You may only need the dispose command.
cmdCounty.Dispose()
Catch ex As Exception
'Catch your error here.
cmdCounty.Connection.Close()
cmdCounty.Dispose()
End Try
gv2.DataSource = ds 'Set the datasource for your GridView control.
gv2.DataBind() 'Bind the data.
Using SqlDataReader and a DataTable
According to your comment, you're code is breaking when you assign the gridview to the cmd.ExecuteReader.
You will need to access your data using a method like this:
Dim rdr as SqlDataReader = cmdCounty.ExecuteReader() 'Declare the SqlDataReader and set it to handle your SqlCommand.
Dim dt as New DataTable 'Initialize a new DataTable. This is where we will place the information we read using the SqlDataReader.
'Make sure you add the columns...
dt.Columns.Add("firstColumnName") 'Create a column for each field you will be retrieving data from.
dt.Columns.Add("secondColumnName")
Dim r as DataRow 'Declare the variable r as a DataRow.
'You may want to insert the line "If rdr.HasRows Then" to check if any data was pulled before attempting to read it.
While rdr.Read() 'Loop through each row in the reader.
r = dt.NewRow() 'Set r to equal a new DataTable in the DataTable we created. Note: This does not actually add the row to the table.
r("firstColumnName") = rdr("firstColumnName") 'Set the values of each column in the current DataRow to equal their corresponding data read from SQL.
r("secondColumnName") = rdr("secondColumnName")
dt.Rows.Add(r) 'Add the DataRow r to the DataTable.
End While 'Loop back until there are no more rows.
gv2.DataSource = dt
gv2.DataBind()
Both of these examples assume you have already created your SqlCommand object and have assigned a working SQL query string and Connection object to it.

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.

ASP.NET DataTable output problem

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)

Resources