How to get DropDownList to copy data from a TextBox? - asp.net

Currently in my Web form I have a cascading drop down list, but I'm focusing on the 1st drop down list for now.
Here is the code to load the list.
Private Sub FillLine() ' load 1st dropdown data
Dim dt As New DataTable
Dim strSql = "select distinct level1_id, [LCODE1]+ ' | '+[LNAME1] as [LCODE1]" _
& " FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP]"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
line.DataSource = dt
line.DataTextField = "LCODE1"
line.DataValueField = "level1_id"
line.DataBind()
line.Items.Insert(0, "")
End If
End Sub
And here is the visual representation of how the data I'm pulling looks like.
| level1_id | LCODE1 |
-----------------------------
| 1 | A01 | Line 1 |
I also want to have the drop down list auto load in the correct value based on URL query string.
My plan is to 1st load the value in an invisible textbox, and instruct drop down list to select the same data based on that textbox using page load event.
'load textbox with query string info
Sub loadFrmQuery()
Dim LID As String = Request.QueryString("LID")
Dim cmd As New SqlCommand("SELECT level1_id " _
& ", level2_id " _
& ", level3_id " _
& "FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP] " _
& "where [LEVEL3_ID] = '" & LID & "'", conn)
conn.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader
While rdr.Read
line_text.Text = rdr("level1_id")
process_text.Text = rdr("level2_id")
equip_text.Text = rdr("level3_id")
End While
conn.Close()
End Sub
'page load event
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("EmpID") Is Nothing Then
Response.Redirect("~/Login.aspx")
Else
If Not IsPostBack Then 'whenever hv dropdownlist, need to have this in load sub, or else won't get ddl data.
FillLine()
loadFrmQuery()
line.DataValueField = line_text.Text
End If
End If
End Sub
But during testing, the drop down list won't load in data. I tried calling out the DataTextField and DataValueField of the drop down list and still no response. What should I do in this case?

Related

The ConnectionString not initialized

Good day All
i have an issue with connection string
I'm getting this exception
The ConnectionString property has not been initialized.
on the RowDataBound of the outer gridview sub routine (VB.NET)
when trying to bind data to inner gridview
the code:
Private Function ChildDataSource(ByVal strCustometId As String, ByVal strSort As String) As SqlDataSource
Dim strQRY As String = ""
Dim connString As String = ConfigurationManager.ConnectionStrings("SiteConnectionString").ConnectionString
Using conn As New SqlConnection(connString)
conn.Open()
strQRY = "SELECT [Sortie].[OdvID],[Sortie].[SortieID]," & "[Sortie].[Fuel],[Sortie].[Captain],[Sortie].[Crew] FROM [Sortie]" & " WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "UNION ALL " & "SELECT '" & strCustometId & "','','','','' FROM [Sortie] WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "HAVING COUNT(*)=0 " & strSort
'Initialize command object
Dim cmd As New SqlCommand(strQRY, conn)
Dim dsTemp As New SqlDataSource()
dsTemp.SelectCommand = strQRY
Return dsTemp
End Using
End Function
This event occurs for each row
Protected Sub gvOdv_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim connString As String = ConfigurationManager.ConnectionStrings("MoyensAeriensConnectionString").ConnectionString
Dim conn As New SqlConnection(connString)
conn.Open()
Dim row As GridViewRow = e.Row
Dim strSort As String = String.Empty
' Make sure we aren't in header/footer rows
If row.DataItem Is Nothing Then
Return
End If
'Find Child GridView control
Dim gv As New GridView()
gv = DirectCast(row.FindControl("gvSorties"), GridView)
'Check if any additional conditions (Paging, Sorting, Editing, etc) to be applied on child GridView
If gv.UniqueID = gvUniqueID Then
gv.PageIndex = gvNewPageIndex
gv.EditIndex = gvEditIndex
'Check if Sorting used
If gvSortExpr <> String.Empty Then
GetSortDirection()
strSort = " ORDER BY " & String.Format("{0} {1}", gvSortExpr, gvSortDir)
End If
'Expand the Child grid
ClientScript.RegisterStartupScript([GetType](), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" & DirectCast(e.Row.DataItem, DataRowView)("OdvID").ToString() & "','one');</script>")
End If
'Prepare the query for Child GridView by passing the Odv ID of the parent row
gv.DataSource = ChildDataSource(DirectCast(e.Row.DataItem, DataRowView)("OdvID").ToString(), strSort)
gv.DataBind()
'Add delete confirmation message for Customer
Dim l As LinkButton = DirectCast(e.Row.FindControl("linkDeleteCust"), LinkButton)
l.Attributes.Add("onclick", "javascript:return " & "confirm('Are you sure you want to delete this Customer " & DataBinder.Eval(e.Row.DataItem, "OdvID") & "')")
End Sub
thanks (I'v been hunting this error for last 3 hours)
It looks like both code snippets use a separate connection string. ChildDataSource uses "SiteConnectionString" and gvOdv_RowDataBound uses "MoyensAeriensConnectionString", hopefully I'm not pointing out the obvious here, but if so, are both of those present in your config file?
When you have created the SqlDataSource dynamically in your first code snippet, You haven't set its ConnectionString property, that's why this error is coming up.
Note that you also haven't assigned any ID to your SqlDataSource. Its better to do this too.
You also need to set the ConnectionString property of SqlDataSource.
Dim dsTemp As New SqlDataSource()
dsTemp.ID = "mySqlSourceControl"
dsTemp.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionStr").ConnectionString
dsTemp.SelectCommand = strQRY
...
Rest of things should also be fine like: web.config has a connection string for the key mentioned [ e.g. ConnectionStr here]
Instead of returning a SQLDataSource as the gridview's datasource, perhaps return a dataset.
Private Function ChildDataSource(ByVal strCustometId As String, ByVal strSort As String) As DataSet
Dim strQRY As String = "SELECT [Sortie].[OdvID],[Sortie].[SortieID]," & "[Sortie].[Fuel],[Sortie].[Captain],[Sortie].[Crew] FROM [Sortie]" & " WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "UNION ALL " & "SELECT '" & strCustometId & "','','','','' FROM [Sortie] WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "HAVING COUNT(*)=0 " & strSort
Dim connString As String = ConfigurationManager.ConnectionStrings("SiteConnectionString").ConnectionString
Using conn As New SqlConnection(connString)
conn.Open()
Using da As New SqlDataAdapter(strQRY, conn)
Using ds As New DataSet
If da.Fill(ds) > 0 Then
Return ds
Else
Return New DataSet
End If
End Using
End Using
End Using
End Function
The method to set the datasource of the child gridview remains the same.

String.Join not working with vbCrLf

I have the following procedure, which works fine. The only part that I am having an issue with is when the CompNames list has more than 1 record. I am trying to use String.Join with vbCrLf but it doesnt work.
Anyone have any ideas or an alternative I could use.
Public Sub gvTeamList_OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim TeamID As Integer
If e.Row.RowType = DataControlRowType.DataRow Then
TeamID = DataBinder.Eval(e.Row.DataItem, "TeamID")
Dim sSQL As String
sSQL = "SELECT C.CompetitionName, CTT.TeamID " & _
"FROM tblCompetition C " & _
"left join tblCompetitionToTeam CTT on C.CompetitionID = CTT.CompetitionID " & _
"left join tblTeam T on CTT.TeamID = T.TeamID " & _
"where CTT.TeamID = " & TeamID
Dim dr = DataClass.GetDataReader(sSQL)
Dim bRows As Boolean = dr.HasRows
Dim CompNames As New List(Of String)
While dr.Read
CompNames.Add(dr("CompetitionName"))
End While
Dim Name As String
If CompNames.Count > 0 Then
For Each Name In CompNames
e.Row.Cells(5).Text = String.Join(vbCrLf, CompNames.ToArray)
Next
End If
'e.Row.Cells(5).Text =
e.Row.Cells(5).ForeColor = Drawing.Color.Yellow
e.Row.Cells(5).BackColor = Drawing.Color.DarkBlue
dr.Close()
End If
End Sub
I have also tried Environment.NewLine and that doesnt work either
It appears you are using a WebForms application. In HTML, a line return generally has no effect because whitespace is ignored (unless it's embedded in certain tags). You want to use <br /> to generate a line break:
e.Row.Cells(5).Text = String.Join("<br />", CompNames.ToArray)
Also, you don't need the For Each loop, because String.Join enumerates the entire array in a single call. It's redundant to run this once for each Name in CompNames.

Creating Control Arrays in Vb 2010 with table column names not reading Rows

I am having problems with Creating Control Arrays and getting the Column Names for a table, I know that my string works as I have used the outputted string straight as a SQL query, the problem lies where it seems not to find any of the rows in the table(that i know are their, using the If lrd.HasRows Then I have seen that it does not find any rows (lrd.HasRows = False). Is their a diffent Connection string for INFORMATION_SCHEMA.COLUMNS ?
'Finds the Column Name
Public Sub findSQLColumnName(ByRef i As Integer, ByRef OutputValue As String, ByVal tableName As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim lrd As SqlDataReader
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Output
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
Call FindConnectionString(con) ' finds connection string
cmd.Parameters.Add(TableNameParm)
cmd.Parameters.Add(LocationParm)
Call SQLSELECT_WHERE("INFORMATION_SCHEMA.COLUMNS", "COLUMN_NAME AS Output, ORDINAL_POSITION", True, " (TABLE_NAME = #Tablename) AND (ORDINAL_POSITION = #Location)", con, cmd, lrd)
Try
' While lrd.Read() ' code writen within here for what is to be done with selected data.
'Call findSQLColumnValue("Output", lrd, OutputValue)
'End While
If lrd.HasRows Then
lrd.Read()
Call findSQLColumnValue("Output", lrd, OutputValue)
lrd.Close()
'Close connection before Redirecting.
Else
lrd.Close()
End If
' Catch ex As Exception
Finally
con.Close()
End Try
End Sub
'Finds the value of a Column
Public Sub findSQLColumnValue(ByRef ColumnName As String, loader As SqlDataReader, ByRef OutputValue As String)
OutputValue = (Convert.ToString(loader(ColumnName))).Trim
End Sub
'Button Click (Creates the control array)
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim SQLCode As New SQLCode
Dim TableLength As Integer
Dim lblText(100) As String
Call SQLCode.SQLFindNoColumns("PatientClinicalinformation", TableLength, lblTitlePatient, lblText)
For i As Int16 = 1 To TableLength
' Create the label control and set its text attribute
Dim Label2 As New Label
Call SQLCode.findSQLColumnName(i.ToString, lblText(i), "PatientClinicalinformation")
Label2.Text = lblText(i)
Dim Literal2 As New Literal
Literal2.Text = "<br />"
' Add the control to the placeholder
PlaceHolder1.Controls.Add(Label2)
Label2.ID = "lbl" & i
PlaceHolder1.Controls.Add(Literal2)
Next
End Sub
'SelectWhere
Public Sub SQLSELECT_WHERE(ByVal Tables As String, ByVal Columns As String, ByVal WHERE As Boolean, ByVal WHEREStatement As String, ByRef connection As SqlConnection, ByRef command As SqlCommand, ByRef loader As SqlDataReader)
connection.Open()
command.Connection = connection
If WHERE = False Then
command.CommandText = " SELECT " & Columns & " FROM " & Tables
End If
If WHERE = True Then
command.CommandText = " SELECT " & Columns & " FROM " & Tables & " WHERE " & WHEREStatement
End If
command.CommandText = command.CommandText
loader = command.ExecuteReader()
End Sub
I found the solution! the code all worked there was a problem with the array TableNameParm
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Output
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
The TableNameParm.Direction should be an input but is set to a Output
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Input
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
It's hard to say without knowing the function SQLSELECT_WHERE, but it's possible one or more of the parameters is not correct. Try skipping that function and use
cmd = New SqlCommand("SELECT ... WHERE", conn)
You can also test the number of rows by using count(*) in the query.

GridView + Access Database

I'm trying to link Access database with GridView control.
Here's the question:
One successful procedure to link database query.
Protected sub Query(ByVal y as string)
Dim da As New OleDbDataAdapter(y, cn)
Dim dt As New DataTable()
da.Fill(dt)
da.Dispose()
cn.Dispose()
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
ListBox1.Visible = True
End sub
What I wanted is to re-run query if the first run returns no value/result in another procedure.
Protected Sub btnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind.Click
x = "SELECT * From Class Where Gender ='Male' And First_name ='James' "
Query(x)
If gridview.rows.count =0 then
x= "SELECT * From Class Where Gender ='Male'"
query(x)
End If
then put result into listbox.
However, I got error of "The ConnectionString property has not been initialized." on da.Fill(dt) when running the second time. First time was successful.
OK I finally got mistake corrected. I gotta Dim cn As New OleDbConnection("Provider = Microsoft.JET.OLEDB.4.0;" & "Data Source = C:\Class.mdb") again to use query instead of once for all queries.
Create and dispose the connection in the same method
Protected Sub Query(ByVal y as string)
Dim dt As New DataTable()
Using cn as New OleDbConnection("your_connection_string"), _
da As New OleDbDataAdapter(y, cn)
da.Fill(dt)
End Using
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Sub

How can I grab the ID of the just deleted record?

This code is intended to grab the ID of the deleted record, the user who deleted the record, and the date and time the record was deleted and insert it into a hostical table.
So far, once a record is deleted, the code grabs more than one deleted record.
Please see my code and what I am doing wrong.
Thanks alot in advance for your help.
Protected Sub GridView1_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles GridView1.RowDeleted
Dim connStr As String = ConfigurationManager.ConnectionStrings("Constr").ConnectionString
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String = ""
' Indicate whether the delete operation succeeded.
If e.Exception Is Nothing Then
Dim strID As String = GridView1.FindControl("ID").Cells(1).Text
'Who deleted a record?
sql += "Insert into Archives ([ID],[choice],[date_stamp],[approved],[chcknum],[DeletedBy],[dateDeleted]) "
sql += " SELECT [ID],[choice],[date_stamp],[approved],[chcknum],[login],getDate() from Depends "
sql += " inner join Emp on Depends.employee_id = Emp.employee_id where login ='" & Session.Item("UserName").ToString & "' and upass = '" & Session.Item("Password").ToString & "' and [ID] = '" & strID & "' "
End If
Response.Write(sql)
Response.End()
Try
cnn = New SqlConnection(connStr)
cnn.Open()
cmd = New SqlCommand(sql, cnn)
cmd.ExecuteNonQuery()
cmd.Dispose()
sql = ""
Catch ex As SqlException
Dim errorMsg As String = "Error in Updation"
errorMsg += ex.Message
Throw New Exception(errorMsg)
Finally
cnn.Close()
End Try
End Sub
My problem, I think, lies in this line of code:
Dim strID As String = GridView1.FindControl("ID").Cells(1).Text
I don't think it is correct.
I'm guessing you're looking for the GridView.DataKeys property. Use it to tell your GridView which column(s) in the data is should use as an unique identifer.
You probably also want to look into a few other optimzations for your code:
Use parameters in your query, don't concatenate a SQL statement like that.
Use the Using statement with your SqlConnection and SqlCommand objects for proper and easy disposal.
You're not achiving anything with the try-catch, in fact you're obscuring the exception stack.
Update:
See the GridViewDeletedEventArgs.Keys Property to get the ID of the deleted row. Is the "ID" column part of the query you're using to bind the GridView?
Here's a better (complete) example:
.aspx:
<asp:GridView ID="GridView1" DataKeyNames="ID" AutoGenerateDeleteButton="true" runat="server">
</asp:GridView>
Code-behind, with some dummy data:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim x() = {New With {.id = 1, .name = "xxx"}, New With {.id = 2, .name = "zzz"}}
GridView1.DataSource = x
GridView1.DataBind()
End If
End Sub
Private Sub GridView1_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
Dim id As Integer = CInt(e.Keys(0))
' Do your stuff!
' Don't forget to rebind the GridView, it will still have the deleted row in Viewstate.
End Sub
End Class
If you are running SQL Server, It might be easier to use a delete trigger on the table.
http://msdn.microsoft.com/en-us/library/aa258254%28v=SQL.80%29.aspx
...deleted and inserted are logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined, that is, the table on which the user action is attempted, and hold the old values or new values of the rows that may be changed by the user action.

Resources