How to find the value of a dropdownlist using FindControl? - asp.net

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

Related

BC30311: Value of Type 'faq' cannot be converted to 'FAQ'

really stuck on this one. The logic doesn't seem to be different from any other Linq to Entity logic I have in the rest of my application. I'm simply writing data into a table called FAQ using Linq to Entity. But I get the message BC30311: Value of Type 'faq' cannot be converted to 'FAQ'. I can't work out what value it means.
Dim objQuestion As TextBox = gvDetails.FooterRow.FindControl("txtFooterQuestion")
Dim objAnswer As TextBox = gvDetails.FooterRow.FindControl("txtFooterAnswer")
Dim objCategory As TextBox = gvDetails.FooterRow.FindControl("txtFooterCategory")
Using DBContext As New fundmatrixEntities
Dim queryFAQ = DBContext.FAQs
Dim oFAQ As New FAQ
queryFAQ.Add(oFAQ)
oFAQ.FAQId = 5
oFAQ.Question = objQuestion.Text
oFAQ.Answer = objAnswer.Text
oFAQ.Category = objCategory.Text
oFAQ.DateCreated = Date.Now
oFAQ.DateUpdated = Date.Now
Try
DBContext.SaveChanges()
BindEmployeeDetails()
lblresult.ForeColor = Drawing.Color.Green
lblresult.Text = "details inserted successfully"
Catch ex As Exception
lblresult.Text = "There was problem inserting the FAQ!"
lblresult.ForeColor = Drawing.Color.Red
End Try
End Using

Dropdownlist loaded from function or method

I have a dropdownlist which I constantly use.
I wrote a method to load this dropdown.
Though when I call the method only the Text part of the item is passed.
This is the method
Public Shared Function ddlLoadResumes() As DropDownList
Dim connString As String = ConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString
Dim conn As SqlConnection = New SqlConnection(connString)
Dim ddSelectResumeList As New DropDownList
Dim dtResumes As New DataTable()
Dim comm As SqlCommand = New SqlCommand("usr_SelectResumeList", conn)
comm.CommandType = CommandType.StoredProcedure
comm.Parameters.Add("#UserName", SqlDbType.VarChar, 50).Value = Membership.GetUser().UserName
Try
Dim daResumes As New SqlDataAdapter(comm)
conn.Open()
daResumes.Fill(dtResumes)
ddSelectResumeList.DataSource = dtResumes
ddSelectResumeList.DataTextField = "ResumeName"
ddSelectResumeList.DataValueField = "Res_ID"
ddSelectResumeList.DataBind()
' Handle the error
Catch ex As Exception
Finally
conn.Close()
End Try
Return ddSelectResumeList
End Function
and this is how I call it
ddSelectResume.DataSource = MailClass.ddlLoadResumes.Items
ddSelectResume.DataBind()
Dim ltitem As ListItem
For Each ltitem In ddSelectResume.Items
Response.Write(ltitem.Value + "-----" + ltitem.Text)
Next returns only the text part
I need both DataTextField and DataValueField.
Thank you in advance
This seems like kind of an odd approach. One thing to resolve your issue would be to just set the ddSelectResume equal to the DropDownList object your Function is returning:
ddSelectResume = MailClass.ddlLoadResumes
Dim ltitem As ListItem
For Each ltitem In ddSelectResume.Items
Response.Write(ltitem.Value + "-----" + ltitem.Text)
Next
Though I think a better approach would be to just have "ddlLoadResumes return the DataTable (dtResumes), and set that as the datasoure of ddSelectResumes (you'd still have to set the DataTextField and DataValueField properties).

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 to populate a text box with value from DB

I am new to asp.net and here I am trying to populate a single text box with a value from database.
I have created this code but not working:
Try
Dim MyCon As New SqlConnection("server = servername; uid = sa; pwd =abc; database = master")
Dim MyCommand As New SqlCommand("Select empFirstName from Employees where empid=2")
MyCon.Open()
Dim MyReader = MyCommand.ExecuteReader()
While MyReader.Read()
Dim sqlda = New SqlDataAdapter()
Dim dt As New Data.DataTable()
Dim ds As New Data.DataSet
sqlda.Fill(ds)
TextBox1.Text = ds.Tables(0).ToString
MyCon.Close()
End While
Please correct the code and tell me where I am wrong.
Kindly suggest me a link if any to read more on this topic for beginners with example.
Try this sample, it will work for you http://geekswithblogs.net/dotNETvinz/archive/2008/09/12/bind-textbox-and-label-control-with-data-from-database.aspx
ds.Tables(0)
will return a DataTable
If you want to get the tablename, write this instead:
ds.Tables(0).TableName
If you want to get value returned, write this kind of code:
ds.Tables(0).Rows(0).Item("empFirstName")
This will store only the 1st row from the database
TextBox1.Text = ds.Tables(0).Rows(0)(0).ToString();
Row(0)(0) indicates to get the 1st row from the 1st column
If the query is returning more than 1 rows then u need to iterate the data table and store it in a List(Of String) instead of an array as you don't know the number of rows returned from the query
Dim EmpFirstName As New List(Of String)
Dim myRow As DataRow
Dim myColumn As DataColumn
For Each myRow in dt.Rows
EmpFirstName.Add(myRow(dt.Columns(0)))
Next

Using a stringbuilder as a parameter to a stored procedure and returning a dataset

I have a couple of problems relating to one of the parameters passing a number of values to a stored procedure and the result that comes back converting to dataset in order for this to be bound to an MS ReportViewer.
The error I am getting says that the the reader is closed.
My relevant code snippet is:
Dim _listOfSites As New StringBuilder()
Dim _resultDataSet As DataSet = New DataSet
Using _conn as New SqlConnection()
_conn.ConnectionString = _connString
Try
For i as Integer = 0 To _sites.Count - 1
_listOfSites.Append(_sites(i))
If _sites.Count > 1 Then
_listOfSites.Append(",")
End If
Next
_conn.Open()
Dim _sqlCommand as SqlCommand = New SqlCommand("GetResults", _conn)
_sqlCommand.Parameters.Add("#Sites", SqlDbType.Varchar).Value = _listOfSites
_sqlCommand.Parameters.Add("#Date", SqlDbType.Date).Value = _date
Dim _reader as SqlDataReader = _sqlCommand.ExecuteReader
While _reader.Read
_resultDataSet.Load(_reader, LoadOption.PreserveChanges, New String() {"RegionalResults"})
End While
_reader.Close()
Can anyone please help?
Thanks
Looks like you should not call _reader.Read as _resultDataSet.Load do it by itself and it could close the SqlDataReader. So instead of
Dim _reader as SqlDataReader = _sqlCommand.ExecuteReader
While _reader.Read
_resultDataSet.Load(_reader, LoadOption.PreserveChanges, New String() {"RegionalResults"})
End While
_reader.Close()
Just write
Using _reader as SqlDataReader = _sqlCommand.ExecuteReader
_resultDataSet.Load(_reader, LoadOption.PreserveChanges, New String() {"RegionalResults"})
End Using
Hope that helps

Resources