error after publishing app: The specified string is not in the form required for an e-mail address. - asp.net

I am trying to create a program to send an email. my program works fine when I run it on local, but display an error after I publish it to the server.
this program trying to send an email inside gridview.
here is the gridview :
checkbox || email1 || email2
checkbox || bla2.smptserver.com || bla3.smptserver.com
checkbox || || bla3.smptserver.com
if email if email in column email1 is not null then the email will be send directly.
if email in column email1 is null then the email will be send to the recipient in column email2.
here is my code so far :
Private Sub sendEmail()
Dim Username2 As String = System.Configuration.ConfigurationManager.AppSettings("username")
Dim Password2 As String = System.Configuration.ConfigurationManager.AppSettings("1234")
Dim Server2 As String = System.Configuration.ConfigurationManager.AppSettings("namesmtp.server.com")
Dim X As Integer
For X = 0 To GridView1.Rows.Count - 1
Dim chkBox As CheckBox = CType(GridView1.Rows(X).Cells(18).Controls(1), CheckBox)
If chkBox.Checked = True Then
Dim email2 As String = ""
Dim no As Integer = CInt(GridView1.Rows(X).Cells(0).Text)
Dim id As String = Trim(GridView1.Rows(X).Cells(1).Text)
Dim name As String = Trim(GridView1.Rows(X).Cells(2).Text)
Dim item As String = Trim(GridView1.Rows(X).Cells(3).Text)
Dim size As String = Trim(GridView1.Rows(X).Cells(4).Text)
Dim qty As String = Trim(GridView1.Rows(X).Cells(5).Text)
Dim clr As String = Trim(GridView1.Rows(X).Cells(6).Text)
Dim type As String = Trim(GridView1.Rows(X).Cells(7).Text)
Dim area As String = Trim(GridView1.Rows(X).Cells(8).Text)
Dim ab As String = Trim(GridView1.Rows(X).Cells(9).Text)
Dim reason As String = Trim(GridView1.Rows(X).Cells(10).Text)
For Each row As GridViewRow In GridView1.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim chkRow As CheckBox = TryCast(row.Cells(18).FindControl("chkCtrl"), CheckBox)
If chkRow.Checked Then
Dim spv As String = Trim(row.Cells(16).Text)
Dim mgr As String = Trim(row.Cells(17).Text)
sql = "update tbl_name set [Attire App] = 'Approved', [Attire Date] = #ADate, [SPV App] = (case when [SPV id] = '' then 'Approved' else [SPV App] end) where No = '" & Convert.ToUInt32(no) & "' and [Badge ID]= '" + Convert.ToString(id) + "' and Uniform = '" + item + "' and [Attire App] is null"
Dim sqlcomm As New SqlCommand(sql, con)
sqlcomm.Parameters.AddWithValue("#ADate", Now.Date)
sqlcomm.ExecuteNonQuery()
End If
End If
Next
If email2 <> "" Then
email2 = Trim(GridView1.Rows(X).Cells(16).Text)
Else
email2 = Trim(GridView1.Rows(X).Cells(17).Text)
End If
Try
Dim EmailMessage As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage
EmailMessage.From = New MailAddress("mail.address#something.com")
EmailMessage.To.Add(email2)
EmailMessage.Subject = "Attire Request"
EmailMessage.IsBodyHtml = True
Dim link As String = "Some link"
EmailMessage.Body = "There is a request for attire from employee. Please approve the request by using the following link Click here "
Dim smtp As New SmtpClient(Server2)
Dim basicAuthenticationInfo As New System.Net.NetworkCredential(Username2, Password2)
smtp.Credentials = basicAuthenticationInfo
smtp.Send(EmailMessage)
Catch ex As Exception
lblError.Text = ex.Message
lblError.Visible = True
End Try
End If
Next
End Sub
column email1 reside on gridview cell 16.
column email2 reside on gridview cell 17.
it's work fine but after I publish it, it's throws an errror.
the error display is 'The specified string is not in the form required for an e-mail address. '
Thanks in advance...

Related

Binding Url to Gridview

I want to bind the url to GridView but I don't know how.
For example when I type the http://localhost:12345/example.aspx?FirstName=John in the url it will give me the result in GridView that shows only with the FirstName "John".
Here's my curent code:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim dt As New DataTable
' Stablish ODBC Connection
Dim con As New OdbcConnection("DRIVER={SQL Server};Server=WJNJPHR8TCX8P\SQLEXPRESS;Database=Fabrics;Integrated Security=True;")
' Query Command
Dim cmd As New OdbcCommand("SELECT * FROM [Client] WHERE [FirstName] = ?", con)
con.Open()
' Gets the path (Example.aspx)
Dim path As String = HttpContext.Current.Request.Url.AbsolutePath
' Gets the host (localhost)
Dim host As String = HttpContext.Current.Request.Url.Host
' Gets the whole url (localhost:24124/Example.aspx)
Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
' Parse the query string variables into a NameValueCollection
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(url)
' Iterate through the collection and shows the result in MsgBox
Dim sb As New StringBuilder()
For Each s As String In qscoll.AllKeys
sb.Append(s & " = " & qscoll(s) & vbCrLf)
Next s
MsgBox(sb.ToString)
' Gets all keys and values in query string and shows it on MsgBox
For Each key As String In HttpContext.Current.Request.QueryString.AllKeys
MsgBox("Key: " + key + " Value: " + Request.QueryString(key))
Next key
Dim FName As String = Request.QueryString("FirstName")
Dim par1 As New OdbcParameter
par1.OdbcType = OdbcType.NVarChar
par1.Value = FName
par1.ParameterName = "#FirtName"
cmd.Parameters.Add(par1)
'Shows the result in Data Grid
dt.Load(cmd.ExecuteReader()) '==> Error: Invalid use of default parameter
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Any help will do!
You can access your query string directly with
Dim firstName as string = Request.QueryString("firstName")
Then you must pass it as a parameter of the query before executing it
Dim par1 As New OdbcParameter
par1.DbType = DbType.String
par1.Value = firstName
par1.ParameterName = "#FirstName"
cmd.Parameters(1) = par1
Hope it helps
Answered my question!
Here's my code:
For Each key As String In HttpContext.Current.Request.QueryString.AllKeys
Dim FName As String = Request.QueryString("FirstName")
Dim par1 As New OdbcParameter With {
.OdbcType = OdbcType.NVarChar,
.Value = FName,
.ParameterName = "#FirstName"
}
cmd.Parameters.Add(par1)
MsgBox("Key: " + key + " Value: " + Request.QueryString(key))
dt.Load(cmd.ExecuteReader())
GridView1.DataSource = dt
GridView1.DataBind()
Next key
#isol Thanks for your help! :)

Handler change Session Variable?

I have this handler:
Public Sub ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim request As HttpRequest = context.Request
Dim response As HttpResponse = context.Response
If (request.QueryString(GestioneConstants.PASSWORD_PARAM) Is Nothing) Then
Dim erroreParamName = GestioneConstants.ERRORE_PASSWORD_PARAM
Dim erroreMessage = GestioneConstants.MESSAGE_PWD_MANCANTE
Dim urlHome = "~/Default.aspx?" & erroreParamName & "=" & erroreMessage
response.Redirect(urlHome, False)
Else
Dim passToFind= request.QueryString(GestioneConstants.PASSWORD_PARAM)
Dim myConn As OdbcConnection
myConn = New OdbcConnection("Driver={Microsoft ODBC for Oracle};Server=SERVER;uid=uid;pwd=password")
myConn.Open
Dim passwordQuery As String = "SELECT PASSWORD as PASSWORD FROM INFOPWD WHERE INFOPWD.PASSWORD = '" & passToFind & "'"
Dim queryCommand As OdbcCommand = New OdbcCommand(passwordQuery,myConn)
Dim reader As OdbcDataReader = queryCommand.ExecuteReader()
Dim risultato = ""
While reader.Read()
risultato = reader("PASSWORD").ToString
End While
reader.Close
myConn.Close
If (risultato Is "") Then
Dim erroreParamName = GestioneConstants.ERRORE_PASSWORD_PARAM
Dim erroreMessage = GestioneConstants.MESSAGE_PWD_ERRATA
Dim urlHome = "~/Default.aspx?" & erroreParamName & "=" & erroreMessage
response.Redirect(urlHome, False)
Else
context.Session("Logged") = True
Dim strURL = "~/Home.aspx"
response.Redirect(strURL, False)
End If
End If
End Sub
Pratically my problem its on:
context.Session("Logged") = True
I just want to set this session variable to true where from the ASP page the user insert the correct password.
But I get the error:
An object reference not set to an instance of an object.
I don't understand why this happens.
Can someone help?
You need to use the Current property:
context.Current.Session("Logged") = True should work.

Error: An exception of type 'System.Data.SqlClient.SqlException' occured in System.Data.dll but was not handled in user code

I'm new to ASP.NET and building a little dynamic website for a salesdepartment to registere their sales for salescompetions.
I have a page, after one is logged in, that consists of a couple of comboboxes/dropdowns and at the buttom a 'SUBMIT' button which I want to trigger a new record in the database with all the selected data. everything seems to go fine for a second but eventually the following error message appears:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Invalid column name 'KunderID'.
Invalid column name 'KundeTypeID'.
Invalid column name 'MachineModellID'.
Invalid column name 'AntallID'.
Invalid column name 'BrukerID'.
It points to the following part (The line starting with MBExec =) in the DBConnection.vb file:
Public Shared Function MBExec(ByVal SQL As String) As String
Dim cmd As New SqlCommand(SQL, MBConn)
MBExec = Convert.ToString(cmd.ExecuteScalar())
cmd.Connection.Close()
End Function
On the sourcecode og the relevant page the relevant part of it is the following (bottom line starting with MBExec) whereby I cannot see that the columnsnames are wrong:
Protected Sub RegisterSale(sender As Object, e As EventArgs)
Dim KundeNavn As DropDownList = DropDownListKundeNavn
Dim TypeKunde As DropDownList = DropDownListTypeKunde
Dim MachineModell As DropDownList = DropDownListMachineModell
Dim Antall As DropDownList = DropDownListAntall
Dim Bruker As DropDownList = DropDownListBruker
If KundeNavn.SelectedItem.Text = "Velg" Then
Dim msg = "Select or add a new customer"
Dim msgTittle = "Missing Customer Name"
MsgBox(msg, MsgBoxStyle.Critical, msgTittle)
Exit Sub
Else
Dim msg1 = "Are you sure to continue?"
Dim title = "Confirm Sale Registration"
Dim style = MsgBoxStyle.YesNo
Dim responce = MsgBox(msg1, style, title)
If responce = MsgBoxResult.Yes Then
Dim msg = "Thank you for your efforts, you are closer to becoming a sales champion!"
Dim msgTittle = "Your Sale has been recorded"
MsgBox(msg, MsgBoxStyle.Information, msgTittle)
'Varibles to hold the DataValueField from the dropboxes
Dim KundeID As Integer
Dim TypeKundeID As Integer
Dim MachineModellID As Integer
Dim AntallID As Integer
Dim BrukerID As Integer
'Converts the DataValueField to an Integer
KundeID = Convert.ToInt32(KundeNavn.SelectedValue.ToString())
TypeKundeID = Convert.ToInt32(TypeKunde.SelectedValue.ToString())
MachineModellID = Convert.ToInt32(MachineModell.SelectedValue.ToString())
AntallID = Convert.ToInt32(Antall.SelectedValue.ToString())
BrukerID = Convert.ToInt32(Bruker.SelectedValue.ToString())
MBExec("INSERT INTO KyoceraSalgReg(KunderID, KundeTypeID, MachineModellID, AntallID, BrukerID) Values (KunderID, KundeTypeID, MachineModellID, AntallID, BrukerID)")
Exit Sub
Else
Exit Sub
End If
End If
End Sub
I would very much appreciate if anybody could help me in the right direction here. If I understand it correctly, somehow the column names are not recognized and I just don't see why.
Cheers:)
Update 1:
MBExec looks like this:
Public Shared Function MBExec(ByVal SQL As String) As String
Dim cmd As New SqlCommand(SQL, MBConn)
MBExec = Convert.ToString(cmd.ExecuteScalar())
cmd.Connection.Close()
End Function
And KunderID datatype is string, selection made from a DropDownList
Try this approach:
MBExec("INSERT INTO KyoceraSalgReg(KunderID, KundeTypeID, MachineModellID, AntallID, BrukerID) Values (#KunderID, #KundeTypeID, #MachineModellID, #AntallID, #BrukerID)")
Use parameterized query to add the values:
cmd.Parameter.AddWithValue("#KunderID", KunderID)
AddWithValue
You may need to make separate instances of the SqlParameter - Example
Protected Sub RegisterSale(sender As Object, e As EventArgs)
Dim KundeNavn As DropDownList = DropDownListKundeNavn
Dim TypeKunde As DropDownList = DropDownListTypeKunde
Dim MachineModell As DropDownList = DropDownListMachineModell
Dim Antall As DropDownList = DropDownListAntall
Dim Bruker As DropDownList = DropDownListBruker
'Varibles to hold the DataValueField from the dropboxes
Dim KunderID As Integer = Convert.ToInt32(KundeNavn.SelectedValue.ToString())
Dim TypeKundeID As Integer = Convert.ToInt32(TypeKunde.SelectedValue.ToString())
Dim MachineModellID As Integer = Convert.ToInt32(MachineModell.SelectedValue.ToString())
Dim AntallID As Integer = Convert.ToInt32(Antall.SelectedValue.ToString())
Dim BrukerID As Integer = Convert.ToInt32(Bruker.SelectedValue.ToString())
'Sets the Selected values from dropdownlist
Dim ParamKunderID = New SqlParameter()
ParamKunderID.ParameterName = "#KunderID"
ParamKunderID.Value = KunderID
Dim ParamTypeID = New SqlParameter
ParamTypeID.ParameterName = "#KundeTypeID"
ParamTypeID.Value = TypeKundeID
Dim ParamMachineModellID = New SqlParameter()
ParamMachineModellID.ParameterName = "#MachineModellID"
ParamMachineModellID.Value = MachineModellID
Dim ParamAntallID = New SqlParameter
ParamAntallID.ParameterName = "#AntallID"
ParamAntallID.Value = AntallID
Dim ParamBrukerID = New SqlParameter
ParamBrukerID.ParameterName = "#BrukerID"
ParamBrukerID.Value = BrukerID
If KundeNavn.SelectedItem.Text = "Velg" Then
Dim msg = "Velg eller legge til en ny kunde"
Dim msgTittle = "Mangler Kundenavn"
MsgBox(msg, MsgBoxStyle.Critical, msgTittle)
Exit Sub
Else
Dim msg1 = "Er du sikker på at du vil fortsette?"
Dim title = "Bekrefte salg registrering"
Dim style = MsgBoxStyle.YesNo
Dim responce = MsgBox(msg1, style, title)
If responce = MsgBoxResult.Yes Then
MBExec("INSERT INTO KyoceraSalgReg(KunderID, KundeTypeID, MachineModellID, AntallID, BrukerID)" & " Values " & "(" & KunderID & "," & TypeKundeID & "," & MachineModellID & "," & AntallID & "," & BrukerID & ")")
Dim msg = "Takk for din innsats, du er nærmere å bli et Salg Mester!"
Dim msgtittle = "Din salget er registrert"
MsgBox(msg, MsgBoxStyle.Information, msgtittle)
End If
End If
End Sub

Web form to console application with timer

i have created a code in asp.net webform
now i want this code to be run in console application
but i don't know
how to invoke my timer
and where to place the code
can someone help me to convert
these code into a console application
Dim con1 As New SqlConnection(_start)
Dim sql12 As String = "SELECT Auction.AuctionID FROM Item INNER JOIN Auction ON Item.ItemID = Auction.ItemID Where Auction.Status='Valid' AND Auction.EndDate<=#endate "
Dim cmd12 As New SqlCommand(sql12, con1)
con1.Open()
cmd12.Parameters.AddWithValue("#endate", DateTime.Now)
Dim query As Integer = cmd12.ExecuteScalar
Dim sql123 As String = "UPDATE Auction SET Status ='Expired' WHERE AuctionID =#auction"
Dim cmd21 As New SqlCommand(sql123, con1)
cmd21.Parameters.AddWithValue("#auction", query)
cmd21.ExecuteNonQuery()
CalculateWinningPrice(query)
WinningBet()
timer1.Enabled = True
Public Sub CalculateWinningPrice(ByVal query As Integer)
Dim price As Integer
Using con1 As New SqlConnection(_start)
con1.Open()
Dim sql1 As String = "SELECT MAX(BiddingPrice) AS Expr1 FROM BID WHERE (AuctionID = #auction)"
Dim cmd1 As New SqlCommand(sql1, con1)
cmd1.Parameters.AddWithValue("#auction", query)
Dim max As Double = Convert.ToDouble(cmd1.ExecuteScalar)
Dim cmd2 As New SqlCommand("SELECT MAX(BiddingPrice) AS Expr1 FROM BID WHERE (BiddingPrice <( SELECT MAX(BiddingPrice) AS Expr2 FROM BID AS BID_1 WHERE (AuctionID = #auction)))", con1)
cmd2.Parameters.AddWithValue("#auction", query)
Dim second As Double = Convert.ToDouble(cmd2.ExecuteScalar)
Dim cmd3 As New SqlCommand("SELECT BuyerID FROM BID WHERE(BiddingPrice =(SELECT MAX(BiddingPrice) AS Expr1 FROM BID AS BID_1 WHERE(AuctionID = #auction)))", con1)
cmd3.Parameters.AddWithValue("#auction", query)
Dim Buyer As Integer = Convert.ToInt32(cmd3.ExecuteScalar)
If max - second = 1 Then
price = second
Else
If max - second > 10 Then
price = second + 1
Else
If max - second > 100 Then
price = second + 10
Else
If max - second > 1000 Then
price = second + 1000
End If
End If
End If
End If
Dim cmd As New SqlCommand("INSERT INTO BID VALUES(#Date, #BiddingPrice,#Status,#AuctionID,#BuyerID,#WinningPrice)")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Date", DateTime.Now)
cmd.Parameters.AddWithValue("#BiddingPrice", max)
cmd.Parameters.AddWithValue("#Status", "Won")
cmd.Parameters.AddWithValue("#AuctionID", query)
cmd.Parameters.AddWithValue("#BuyerID", Buyer)
cmd.Parameters.AddWithValue("#WinningPrice", price)
cmd.Connection = con1
cmd.ExecuteNonQuery()
End Using
End Sub
then calculate winning price
Private Sub WinningBet()
Dim Email As String
Dim auction1 As Integer = Convert.ToInt32(lblauction.Text)
Using con1 As New SqlConnection(_start)
con1.Open()
Dim sql1 As String = "SELECT TOP (1) Member.Email, BID.BidID FROM BID INNER JOIN Auction ON BID.AuctionID = Auction.AuctionID INNER JOIN Buyer ON BID.BuyerID = Buyer.BuyerID INNER JOIN Member ON Buyer.MemberID = Member.MemberID WHERE(Auction.AuctionID = #auction) and (BID.WinningPrice <>0) ORDER BY BID.BidID DESC"
Dim sqlcommand As New SqlCommand(sql1, con1)
sqlcommand.Parameters.AddWithValue("#auction", auction1)
Email = sqlcommand.ExecuteScalar()
End Using
Dim [to] As String = Email
Dim from As String = "virgoplaza11#gmail.com"
Dim password As String = ""
Dim subject As String = "BID"
Dim body As String = "Your bid has been Successfull Login to shoppingCart to Make Payment"
Dim email1 As New Thread(Sub() SendEmail1([to], from, password, subject, body))
email1.IsBackground = True
email1.Start()
End Sub
Private Sub SendEmail1(ByVal [to] As String, ByVal from As String, ByVal password As String, ByVal subject As String, ByVal body As String)
Using mm As New MailMessage(from, [to])
mm.Subject = subject
mm.Body = body
mm.IsBodyHtml = False
Dim smtp As New SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
Dim NetworkCred As New NetworkCredential(from, password)
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 587
smtp.Send(mm)
End Using
End Sub
To use the Forms timer:
Add a reference to System.Windows.Forms
Imports System.Windows.Forms
For the Web.UI timer:
Add references to System.Web and System.Web.Extensions
Imports System.Web.UI
At module level declare the new timer:
Dim timer1 As New Timer

Why I get SQL error message based on Div color style?

I was verify if the boolean is True or False. If it false, it will change the server Name text to color red, if True, it doesn't change color. The SQL was able to read server Name that doesn't change text color but couldn't read the server Name colored red text and got SQL error message,
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near 'red'.
Here is the VB code:
Dim sqlConn As New System.Data.SqlClient.SqlConnection((ConfigurationManager.ConnectionStrings("SOCT").ConnectionString))
Dim strSqlSecondary As String = "SELECT [Name], [Compliance] FROM [dbo].[ServerOwners] where SecondaryOwner like #uid order by [name]"
Dim cmdSecondary As New System.Data.SqlClient.SqlCommand(strSqlSecondary, sqlConn)
cmdSecondary.Parameters.AddWithValue("#uid", TNN.NEAt.GetUserID())
Dim dr As System.Data.SqlClient.SqlDataReader
Try
sqlConn.Open()
Dim root As TreeNode
Dim rootNode As TreeNode
Dim firstNode As Integer = 0
'Load Primary Owner Node
'Create RootTreeNode
dr = cmdSecondary.ExecuteReader()
If dr.HasRows Then
'Load Secondary Owner Node
'Create RootTreeNode
root = New TreeNode("Secondary Owner", "Secondary Owner")
TreeViewGroups.Nodes.Add(root)
root.SelectAction = TreeNodeSelectAction.None
rootNode = TreeViewGroups.Nodes(firstNode)
'populate the child nodes
While dr.Read()
Dim child As TreeNode = New TreeNode(dr("Name"), dr("Name"))
Dim complianceFlag As Boolean
If Boolean.TryParse(dr("Compliance"), complianceFlag) Then
' Yes, compliance value is a Boolean, now set color based on value
If Not complianceFlag Then
child.Text = "<div style='color:red'>" + child.Text + "</div>"
End If
End If
rootNode.ChildNodes.Add(child)
child.SelectAction = TreeNodeSelectAction.None
End While
dr.Close()
The error came from this line code because it read "red":
child.Text = "<div style='color:red'>" + child.Text + "</div>"
The child node text is passing when I click link to update,
Protected Sub LinkButtonConfirm_Click(sender As Object, e As System.EventArgs) Handles LinkButtonConfirm.Click
hide()
PanelCompliance.Visible = True
PanelDisplayGrid.Visible = True
'display the servers
Dim sqlConn As New System.Data.SqlClient.SqlConnection((ConfigurationManager.ConnectionStrings("SOCT").ConnectionString))
Dim strSql As New StringBuilder
strSql.Append("Select [Name] , [ApplicationName] , [Environment], [Description], [TechMgmtTeam] , [PrimaryOwner], [PPhone], [SecondaryOwner], [SPhone], [Queue], [Crit] from dbo.ServerOwners where")
'Loops Through all Selected items and appends to sql statement
Dim x As Integer = 0
For Each item As TreeNode In TreeViewGroups.CheckedNodes
If item.Depth = 0 Then
Else
'append to select statement
strSql.Append(" [Name]='" & item.Text & "' or ")
x = x + 1
End If
Next
If x = 0 Then
hide()
LabelError.Text = "Please select at least one server in the left pane."
PanelError.Visible = True
Else
strSql.Append(" [Name]='Blank' order by [name]")
Try
sqlConn.Open()
Dim cmd As New System.Data.SqlClient.SqlCommand(strSql.ToString(), sqlConn)
Dim a As New SqlClient.SqlDataAdapter(cmd)
Dim datTab As New DataTable
a.Fill(datTab)
Session("Table") = datTab
GridViewDisp.DataSource = datTab
GridViewDisp.DataBind()
Catch ex As Exception
hide()
LabelError.Text = ex.ToString()
PanelError.Visible = True
Finally
sqlConn.Close()
sqlConn.Dispose()
End Try
End If
End Sub
If I get rid of Div tag, everything is work fine except there won't be colored red. How they able to read Div style which they should ignore the style and focus on child text. Is there a way to fix?
If you store the Name in the .Tag property of the child, you get to be able to use it regardless of what you do to the .Text of the child:
While dr.Read()
Dim myName as String = dr("Name")
Dim child As TreeNode = New TreeNode(myName , myName)
child.Tag = myName
Then in LinkButtonConfirm_Click
Dim x As Integer = 0
For Each item As TreeNode In TreeViewGroups.CheckedNodes
If item.Depth <> 0 Then
'append to select statement
strSql.Append(" [Name]='" & CStr(item.Tag) & "' or ")
x = x + 1
End If
Next
But you should still be adding the CStr(item.Tag) as SQL parameters. You already have a counter x in the loop which you can use to construct parameter names ("#p0", "#p1" etc.).
Edit: which would result in the Click handler looking something like
Protected Sub LinkButtonConfirm_Click(sender As Object, e As System.EventArgs) Handles LinkButtonConfirm.Click
hide()
PanelCompliance.Visible = True
PanelDisplayGrid.Visible = True
'display the servers
Dim sqlConn As New System.Data.SqlClient.SqlConnection((ConfigurationManager.ConnectionStrings("SOCT").ConnectionString))
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim strSql As New StringBuilder
Dim qryBase = <sql>
SELECT [Name]
,[ApplicationName]
,[Environment]
,[Description]
,[TechMgmtTeam]
,[PrimaryOwner]
,[PPhone]
,[SecondaryOwner]
,[SPhone]
,[Queue]
,[Crit]
FROM dbo.ServerOwners
WHERE
</sql>.Value
strSql.Append(qryBase & " ")
'Loop through all Selected items and append to sql statement
Dim x As Integer = 0
Dim nLastCheckedNode As Integer = TreeViewGroups.CheckedNodes.Count - 1
For Each item As TreeNode In TreeViewGroups.CheckedNodes
If item.Depth <> 0 Then
'append to select statement
Dim paramName As String = "#p" & x.ToString()
strSql.Append("[Name] = " & paramName)
If x <> nLastCheckedNode Then
' we have another node to look at, so add " OR "
strSql.Append(" OR ")
End If
'TODO: set the correct SqlDbType and the correct .Size
cmd.Parameters.Add(New SqlParameter With {.ParameterName = paramName,
.SqlDbType = SqlDbType.NVarChar,
.Size = 20,
.Value = CStr(item.Tag)})
x += 1
End If
Next
If x = 0 Then
hide()
LabelError.Text = "Please select at least one server in the left pane."
PanelError.Visible = True
Else
strSql.Append(" ORDER BY [Name]")
Try
sqlConn.Open()
cmd.Connection = sqlConn
cmd.CommandText = strSql.tostring()
Dim a As New SqlClient.SqlDataAdapter(cmd)
Dim datTab As New DataTable
a.Fill(datTab)
Session("Table") = datTab
GridViewDisp.DataSource = datTab
GridViewDisp.DataBind()
Catch ex As Exception
hide()
LabelError.Text = ex.ToString()
PanelError.Visible = True
Finally
sqlConn.Close()
sqlConn.Dispose()
End Try
End If
End Sub
#Andrew Morton - Your theory are correct about error in strSql.Append(" [Name]='" & item.Text & "' or ") in LinkButtonConfirm_Click. I changed to strSql.Append(" [Name]='" & item.Value & "' or ") by replacing Text to Value. Now everything worked!

Resources