Visual Basic ASP.NET 4 Request.Form() - asp.net

this may sound like a silly question but i am learning Visual Basic ASP.NET 4 and i have been asked to create a DropDownList which obtains information from a table using SQL. I cant seem to pull the selected item from the dropdownlist and show it on the screen using Request.Form.
I have tried this..
Dim selItem As String = Request.Form("DDList")
Response.Write(selItem)
but this does not show anything on screen. Please help as i am struggling with this.
I have added my dropdownlist as follows:
<asp:DropDownList ID="DDList" runat="server" Width="201px">
</asp:DropDownList>
<asp:DropDownList ID="DDList2" runat="server" Width="145px">
</asp:DropDownList>
My Class/Function
Public Class sqlFunc
Public Shared Function tableData() As DataSet
Dim oraConnect As New OracleConnection
oraConnect.ConnectionString = ConfigurationManager.ConnectionStrings("smart_dev").ConnectionString
Dim oraCommand As New OracleCommand
oraCommand.Connection = oraConnect
oraCommand.CommandType = Data.CommandType.Text
Dim lsSQL As String = ""
lsSQL = "SELECT code, description FROM ref_code WHERE domain = 'SPECIALTY'"
oraCommand.CommandText = lsSQL
Dim da As New OracleDataAdapter(oraCommand)
Dim ds As New DataSet
da.Fill(ds)
Return ds
End Function
What i am using on my .aspx.vb page;
Dim dsData1 As New DataSet
dsData1 = tableData()
DDList.DataSource = dsData1
DDList.DataValueField = "code"
DDList.DataTextField = "description"
DDList.DataBind()
DDList.Items.Insert(0, New ListItem(String.Empty, String.Empty))
DDList.SelectedIndex = 0

You don't need to get the selected value using Request.Form if you are using an asp:DropDown ASP.net control. All you have to do is:
Dim selItem As String = DDList.SelectedValue
Response.Write(selItem)
If you really want to use Request.Form, do it like this:
Dim selItem As String = Request.Form(DDList.ClientID)
Response.Write(selItem)
Also, make sure you have ViewState enabled and that you do not rebind the DropDown at PageLoad when there is a PostBack:
Sub Page_Load
If Not IsPostBack
' Bind your DropDown here
End If
End Sub

Related

How to find the value of a dropdownlist using FindControl?

I am working on a website with VB.NET and ASP.NET. I currently have recurring DropDownLists for the user to provide input.
The design is recurring. These DropDownLists get their values from a database table, Everything with the Web interface is working except for writing these recurring values to the database - that is just to give you some background.
I have set the ID's of each DropDownList like so:
FrequencyList.ID = String.Concat("FreqList", DBReader(0))
That is in a loop while reading the DatabaseReader.
This is what I'm having issues with (please note I simplified the code down to make it easier to read:
Dim i As Integer
DBCommand = New SqlCommand()
DBCommand.Connection = DBConnection
DBCommand.CommandType = Data.CommandType.StoredProcedure
DBCommand.CommandText = "StoredProcedureName"
DBConnection.Open()
For i = 1 To AspectTableLength
Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("#nFrequencyID", SqlDbType.Int)
ParamFrequencyID.Value = FindControl("FreqList" & Convert.ToString(i))
ParamFrequencyID.Direction = ParameterDirection.Input
Next
The FindControl("FreqList" & Convert.ToString(i)) variable is incorrect because it does not access the value - and adding .SelectedItem.Value does not work.
I got help from a developer.
Dim MyControls As ControlCollection = Panel.Controls
Dim Number As Integer 'this is the same as "DBReader(0)"
For Each MyControl As Control In MyControls
If MyControl.ID Is Nothing Then
Else
If MyControl.ID.StartsWith("Span") Then
Number = Replace(MyControl.ID, "Span", "")
Dim Freq As DropDownList = PanelMain.FindControl(“FreqList” & Number)
Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("#nFrequencyID", SqlDbType.Int)
ParamFrequencyID.Value = Freq.SelectedIndex
ParamFrequencyID.Direction = ParameterDirection.Input
DBCommand.ExecuteNonQuery()
DBCommand.Parameters.Clear()
End If
End If
Next
DBConnection.Close()

Asp.net Telerik Radsearchbox not filter properly

I'm using radsearchbox as a control in my site for search trough db. I used a object data source as radsearchbox's datasource. the aspx code is here:
<telerik:RadSearchBox ID="RadSearchBox1" runat="server"
DataSourceID="ObjectDataSourceSearch"
DataTextField="Name" DataValueField="ID"
EmptyMessage="search here"
Skin="Silk" MinFilterLength="3">
</telerik:RadSearchBox>
<asp:ObjectDataSource ID="ObjectDataSourceSearch" runat="server"
SelectMethod="detail" TypeName="InStore">
</asp:ObjectDataSource>
And detail function is:
Function detail() As List(Of info)
Dim All_info As New List(Of info)
Dim _inf As New info
_inf.ID = 1
_inf.Name = "aaa"
All_info.Add(_inf)
Dim _inf2 As New info
_inf2.ID = 100
_inf2.Name = "bbb"
All_info.Add(_inf2)
Return All_info
End Function
And when I typed any text in radsearchbox, It displays all items in the list.("aaa" and "bbb")
why???
Yes. it will display everything in the list, because in SelectMethod you are setting the function detail(). The function detail is returning the whole list.
To overcome this you can use the OnSearch event handler of the radseachbox or simply use the Linq to filter the result and then return the filtered list.
I don't know about your scenario, but this is my guess. try this code
Protected Function Search(sender As Object, e As SearchBoxEventArgs) As List(Of info)
Dim searchtext As String = e.text
Dim filteredinfo As New List(Of info)()
Dim searchresult As New List(Of info)()
filteredinfo = detail()
searchresult = filteredinfo.where(Function(res) res.Contains(searchtext))
searchresult += filteredinfo.where(Function(res1) res1.Contains(searchtext))
Return searchresult
End Function
And dont forgot to paste this code in OnSearch event handler of radsearchbox.

ASP.Net object reference error when writing data to xml file via Gridview Empty data template

I have an Editable GridView control that functions off of an XML file. The GridView contains an empty-data-template given that the xml file contains no data on page load. The empty-data-template consist of two textbox controls and a link-button for placing data into the xml file, and thus should cause the Gridview to display. My problem is that when I click the link button, I get an Object-reference related error in response to this line: Dim oDr As DataRow = oDs.Tables("po").NewRow ...the full event handler, I provided below:
The code behind:
Public Sub writeStartpoNum()
Dim startpoNumID As String = DirectCast(gvPurchaseOrderNum.Controls(0).Controls(0).FindControl("txtStartpoNumID"), TextBox).Text
Dim startpoNum As String = DirectCast(gvPurchaseOrderNum.Controls(0).Controls(0).FindControl("txtStartpoNum"), TextBox).Text
Dim oDs As New DataSet()
Dim xmlPath As String = MapPath("~/xml/newShipment.xml")
If Not System.IO.File.Exists(xmlPath) Then
oDs.DataSetName = "newShipmentNotification"
oDs.Tables.Add("pos")
oDs.Tables("pos").Columns.Add("pos_Id")
oDs.Tables("pos").Columns("pos_Id").ColumnMapping = MappingType.Hidden
oDs.Tables.Add("po")
oDs.Tables("po").Columns.Add("ponumberID")
oDs.Tables("po").Columns.Add("pos_Id")
oDs.Tables("po").Columns("pos_Id").ColumnMapping = MappingType.Hidden
oDs.Tables("po").Columns.Add("ponumber")
Dim pos_po As DataRelation = oDs.Relations.Add("pos_po", oDs.Tables("pos").Columns("pos_Id"), _
oDs.Tables("po").Columns("pos_Id"))
pos_po.Nested = True
Dim oDrs As DataRow = oDs.Tables("pos").NewRow
oDrs("pos_Id") = 0
oDs.Tables("pos").Rows.Add(oDrs)
Else
oDs.ReadXml(Server.MapPath("~/xml/newShipment.xml"))
End If
Dim oDr As DataRow = oDs.Tables("po").NewRow
oDr("ponumberID") = startpoNumID
oDr("ponumber") = startpoNum
oDr("pos_Id") = 0
oDs.Tables("po").Rows.Add(oDr)
oDs.WriteXml(Server.MapPath("~/xml/newShipment.xml"))
gvPurchaseOrderNum.DataSource = oDs.Tables("po")
gvPurchaseOrderNum.DataBind()
End Sub
...this is the design for the empty-data-template in the Gridview:
<emptydatatemplate>
<b>Enter Purchase Order Number:</b> <br />
<asp:TextBox ID="txtStartpoNumID" runat="server"></asp:TextBox>
<asp:TextBox ID="txtStartpoNum" runat="server"></asp:TextBox><br />
<asp:LinkButton ID="lnkpro" runat="server" OnClick="writeStartpoNum" Text="Add Purchase order Number"></asp:LinkButton>
<br /><br />
</emptydatatemplate>
...this is how the xml reflects on page load as a results of a function that clears the xml file of any data if the xml file contains data on page load.
<?xml version="1.0" standalone="yes"?>
<newShipmentNotification>
<pos />
</newShipmentNotification>
...As I mentioned, when debugged - the issue stems from the following line
Dim oDr As DataRow = oDs.Tables("po").NewRow
The xml is build out, via the conditional statement. What I cannot figure is why the dataset variable (oDs), even though it reflects the pos table when viewed in debug mode, still generates an object-reference related error. Please provide some direction as to what I may be doing wrong here or if there is something I'm missing. Thanks
The issue is when you have the xml file without 'po' node. You can move the node to a new
method like:
Private Function CreatePOSDataset() As DataSet
Dim oDs As New DataSet()
oDs.DataSetName = "newshipmentnotification"
oDs.Tables.Add("pos")
oDs.Tables("pos").Columns.Add("pos_Id")
oDs.Tables("pos").Columns("pos_Id").ColumnMapping = MappingType.Hidden
oDs.Tables.Add("po")
oDs.Tables("po").Columns.Add("ponumberID")
oDs.Tables("po").Columns.Add("pos_Id")
oDs.Tables("po").Columns("pos_Id").ColumnMapping = MappingType.Hidden
oDs.Tables("po").Columns.Add("ponumber")
Dim pos_po As DataRelation = oDs.Relations.Add("pos_po", oDs.Tables("pos").Columns("pos_Id"), _
oDs.Tables("po").Columns("pos_Id"))
pos_po.Nested = True
Dim oDrs As DataRow = oDs.Tables("pos").NewRow
oDrs("pos_Id") = 0
oDs.Tables("pos").Rows.Add(oDrs)
CreatePOSDataset = oDs
End Function
And call the method when 'po' node does not exist:
Public Sub writeStartpoNum(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim startpoNumID As String = DirectCast(gvPurchaseOrderNum.Controls(0).Controls(0).FindControl("txtStartpoNumID"), TextBox).Text
Dim startpoNum As String = DirectCast(gvPurchaseOrderNum.Controls(0).Controls(0).FindControl("txtStartpoNum"), TextBox).Text
Dim oDs As New DataSet()
Dim xmlPath As String = MapPath("~/xml/newshipmentnotification.xml")
If Not System.IO.File.Exists(xmlPath) Then
oDs = CreatePOSDataset()
Else
oDs.ReadXml(Server.MapPath("~/xml/newshipmentnotification.xml"))
If oDs.Tables("po") Is Nothing Then
oDs = CreatePOSDataset()
End If
End If
Dim oDr As DataRow = oDs.Tables("po").NewRow
oDr("ponumberID") = startpoNumID
oDr("ponumber") = startpoNum
oDr("pos_Id") = 0
oDs.Tables("po").Rows.Add(oDr)
oDs.WriteXml(Server.MapPath("~/xml/newshipmentnotification.xml"))
gvPurchaseOrderNum.DataSource = oDs.Tables("po")
gvPurchaseOrderNum.DataBind()
End Sub

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.

how do i display the "On Offer" indicator when the product is on offer in the database of asp.net?

I need to display the "on Offer" indicator next to the product in the gridview if the product has a number "1" in the "Offered" column in the database. if it is zero, then don't display. is there some way to achieve that? thanks.
In my product listing page:
Dim objCat As New Category
Dim objProduct As New Product
Dim i As Integer
Dim boolError As Boolean = False
objCat.ID = CType(Request.QueryString("CatID"), Integer)
' get details of the category
objCat.GetDetails()
' Display the category name
lblCatName.Text = objCat.Name
lblCatName2.Text = objCat.Name
' Display the category description
lblCatDesc.Text = objCat.Description
objCat.GetOfferedProducts()
For i = 0 To gvProduct.Rows.Count - 1
' Get the ProductId from the first cell
objProduct.ID = gvProduct.Rows(i).Cells(0).Text
Dim lblOffer As Label
lblOffer = CType(gvProduct.Rows(i).FindControl("lblOffer"), Label)
If objCat.Offered = "1" Then
lblOffer.Visible = True
Else
lblOffer.Visible = False
End If
Next
gvProduct.DataSource = objCat.GetProducts()
gvProduct.DataBind()
in my category class:
Public Sub GetOfferedProducts()
' Define a conection to database
' Read connection string from the web.config file.
Dim strConn As String
strConn = ConfigurationManager.ConnectionStrings("AppDb").ToString
Dim conn As New SqlConnection(strConn)
' Retrieve details of a given Category ID from the database
Dim strSql As String
strSql = "SELECT * FROM CatProduct cp INNER JOIN Product p " & _
"ON cp.ProductID=p.ProductID INNER JOIN Category c ON cp.CategoryID=c.CategoryID " & _
"WHERE cp.CategoryID=#CategoryID"
' Define an Command object to execute the SQL statement
Dim cmd As New SqlCommand(strSql, conn)
' Add parameter to the SQL command
cmd.Parameters.AddWithValue("#CategoryID", ID)
' Define a data adapter to fetch data
Dim da As New SqlDataAdapter(cmd)
' Define a data set to hold the data fetched
Dim ds As New DataSet
' Open database connection
conn.Open()
da.Fill(ds, "CatProduct")
' Close the database connection
conn.Close()
If ds.Tables("CatProduct").Rows.Count <> 0 Then
Name = ds.Tables("CatProduct").Rows(0)("CatName")
Description = ds.Tables("CatProduct").Rows(0)("CatDesc")
ImageFile = ds.Tables("CatProduct").Rows(0)("CatImage")
Offered = CType(ds.Tables("CatProduct").Rows(0)("Offered"), Integer)
End If
I would hook up the gridview's OnRowDataBound in your aspx page:
<asp:gridview id="MyGridView"
autogeneratecolumns="true"
allowpaging="true"
onrowdatabound="MyGridView_RowDataBound"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" id="lblOffer"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Then in the code behind you could do something like this:
void MyGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var lbl = e.Row.FindControl("lblOffer");
If objCat.Offered = "1" Then
lbl.Visible = True
Else
lbl.Visible = False
End If
}
}
Hope that helps!!
There are various ways to make this happen. Basically, you're just looking to conditionally show/hide an element in the grid.
Which of the many ways to do this happens to be the best way entirely depends on how you're retrieving, binding to and displaying your data. You can put the logic in the business layer (a certain property is set or null based on business rules, etc.), in your data binding code (if you're looping through records for the display or something, such as in an ItemDataBound handler), in your display code (if you're just declaring everything in the aspx and just need to toss in an Eval and a conditional), etc.

Resources