asp.net vb.net gridview - can't sort! - asp.net

I try to make this gridview sortable, but it simply doesn't work, anyone know why?
Dim sql As String = "SELECT Product_ID, Code, Trade_Name "
sql = sql & "FROM Product "
sql = sql & "WHERE Category = ? "
Dim conn As String = WebConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim dad As New OleDbDataAdapter(sql, conn)
dad.SelectCommand.Parameters.AddWithValue("?", CatID)
Dim dtblProduct As New DataTable()
dad.Fill(dtblProduct)
Dim grdProducts As New GridView
grdProducts.ID = "grdProducts"
grdProducts.CellPadding = 5
grdProducts.CellSpacing = 5
grdProducts.GridLines = GridLines.None
grdProducts.AutoGenerateColumns = False
grdProducts.HeaderStyle.HorizontalAlign = HorizontalAlign.Left
grdProducts.EmptyDataText = "No Products Available."
grdProducts.DataSource = dtblProduct
Dim dataNavigateUrlFields() As String = {"Product_ID"}
Dim blnfirstCol As Boolean = True
Dim strPageResolveURL As String = String.Empty
Dim strLnkSelectText As String = String.Empty
For Each col As Data.DataColumn In dtblProduct.Columns
If blnfirstCol Then
Dim lnkSelect As New HyperLinkField
With lnkSelect
.Text = _strAction
.DataNavigateUrlFields = dataNavigateUrlFields
.DataNavigateUrlFormatString = Page.ResolveUrl(_strDirectPage & ".aspx?ProductID={0}&Cat=" & CatID)
End With
grdProducts.Columns.Add(lnkSelect)
blnfirstCol = False
Else
Dim myBoundField As New BoundField()
With myBoundField
Select Case col.ColumnName
Case "CODE"
.HeaderText = "Code"
.ItemStyle.Width = 100
.HtmlEncode = False
Case "TRADE_NAME"
.HeaderText = "Trade Name"
.ItemStyle.Width = 200
End Select
.DataField = col.ColumnName
.Visible = True
End With
grdProducts.Columns.Add(myBoundField)
End If
Next
grdProducts.AllowSorting = True ' Should already be true, but this doesnt help
grdProducts.DataBind()
It's frustrating!

I think you are not assigning SortExpression property in Columns.
Please check this example for more detail.
In your example, just add
.SortExpression= col.ColumnName
below
.DataField = col.ColumnName

Since you are adding columns manually, you have to set the SortExpression property for each of them. See last note here.

Related

Select binary image from database and display in Image control

I I am selecting a binary Image from the database with a SELECT query and I would like to display it in a webform but specifically a image control.
This is my code for selecting the image along with other attributes:
Protected Sub btnSearchEmployee_Click(sender As Object, e As EventArgs)
Dim bytes As Byte()
Using br As BinaryReader = New BinaryReader(FileUpload1.PostedFile.InputStream)
bytes = br.ReadBytes(FileUpload1.PostedFile.ContentLength)
End Using
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings(##).ToString())
conn.Open()
Dim cmd As New SqlCommand("SELECT EmployeeCodes.ID , Departments.ShortDescription , Departments.Code AS [Department Code] , EmployeeCodes.FirstName , EmployeeCodes.LastName , EmployeeCodes.EmployeeID , EmployeeCodes.Code , EmployeePhoto.Photo FROM EmployeeCodes,EmployeevsPositionLink , PositionCodes , Departments , EmployeePhoto WHERE EmployeePhoto.ID = EmployeeCodes.ID AND EmployeevsPositionLink.EmployeeID = EmployeeCodes.ID AND EmployeevsPositionLink.PositionID = PositionCodes.ID AND PositionCodes.DepartmentCode = Departments.Code AND EmployeeCodes.TerminationDate Is Null AND EmployeevsPositionLink.PositionNumber = '1' AND EmployeeCodes.Company IN (1,3) AND (EmployeeCodes.Code = #code)", conn)
cmd.Parameters.AddWithValue("#code", txtSearchEmployee.Text)
Dim adapter As New SqlDataAdapter(cmd)
Dim tbl As New DataTable()
adapter.Fill(tbl)
If tbl.Rows.Count() > 0 Then
lblID.Text = tbl.Rows(0)(0).ToString()
txtName.Text = tbl.Rows(0)(3).ToString()
txtSurname.Text = tbl.Rows(0)(4).ToString()
txtIDNo.Text = tbl.Rows(0)(5).ToString()
txtCostCentre.Text = tbl.Rows(0)(2).ToString()
txtDepartment.Text = tbl.Rows(0)(1).ToString()
txtClockNo.Text = tbl.Rows(0)(6).ToString()
Else
lblSearchEmployee.Visible = True
lblSearchEmployee.Text = "No employee found with the number" + " " + txtSearchEmployee.Text
End If
conn.Close()
End Using
End Sub

Validate that textbox has numeric value in vb.net and compare value with database

enter image description hereI'm trying to validate a textbox where users will put an ID. The ID has to be numeric and at the same time compare to a valid ID in the database. When I was just validating for numeric, I didn't have any problems. But now that I have two conditions, my code doesn't work properly. Whenever I type in letters in the textbox and click a button, it gives me an error. The boolean is throwing me off lol. Below is my code:
Thank you in advance.
Protected Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
Dim dt As DataTable
Dim dr As DataRow
Dim Conn As New SqlConnection("Data Source=Computer;Initial Catalog=Catalog;Persist Security Info=True;User ID=userid;Password=password")
Dim cmd As New SqlCommand("SELECT COUNT(*) FROM [tbl] WHERE [ID]=#Value", Conn)
cmd.Parameters.Add("#Value", SqlDbType.NVarChar).Value = txtId.Text
Conn.Open()
Dim valueExistsInDB As Boolean = CBool(CInt(cmd.ExecuteScalar()) > 0)
Conn.Close()
If (IsNumeric(txtId.Text)) AndAlso valueExistsInDB = True AndAlso txtId.Text IsNot Nothing Then
dt = GetDataTable("SELECT ID, LEFT(SANZ_ID, PATINDEX('%.%', SANZ_ID) -1) AS City, CASE WHEN ST_DIR_ID = 1 THEN 'NB' WHEN ST_DIR_ID = 2 THEN 'SB' WHEN ST_DIR_ID = 3 THEN 'EB' WHEN ST_DIR_ID = 4 THEN 'WB' END AS ST_DIR, STREET_OF_TRAVEL, CROSS_STREET, (SELECT TOP 1 CASE WHEN STATUS_ID = 1 THEN 'F' WHEN STATUS_ID = 2 THEN 'P' WHEN STATUS_ID = 3 THEN 'I' WHEN STATUS_ID = 4 THEN 'N' WHEN STATUS_ID = 5 THEN 'A' END FROM tbl where dbo.tbl.ID=ID) AS STATUS FROM tbl WHERE ID=" & txtId.Text)
dr = dt.Rows(0)
labelStreet.Text = dr("street_of_travel")
labelCrossStreet.Text = dr("cross_street")
labelCity.Text = dr("city")
labelDir.Text = dr("st_dir")
labelAda.Text = dr("STATUS")
'dropdownStatus.SelectedValue=
dropdownStatus.Visible = True
txtNotes.Visible = True
btnSave.Visible = True
Else
MessageBox.Show("ID not found! Please input a valid ID.")
End If
End Sub
If ID is a numeric field then you should pass a numeric parameter not an NVarChar one
' First try to convert the input text to an integer '
' this should be done here before acting on the db '
Dim id As Integer
if Not Int32.TryParse(txtId.Text, id) Then
MessageBox.Show("Error, not a valid number")
return
End If
Dim cmdText = "SELECT COUNT(*) FROM [tbl] WHERE [ID]=#Value"
Using Conn = New SqlConnection(....)
Using cmd As New SqlCommand(cmdText, Conn)
cmd.Parameters.Add("#Value", SqlDbType.Int).Value = id
Conn.Open()
Dim valueExistsInDB = CBool(CInt(cmd.ExecuteScalar()) > 0)
' At this point you don't need anymore to check if the input value'
' is numeric and your if is more simple.....'
if valueExistsInDB Then
......
... continue with your code ....
Else
MessageBox.Show("ID not found! Please input a valid ID.")
End if
End Using
End Using

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

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...

How to load the state of checkboxlist in database asp.net?

got 2 checkboxlists , each checkbox has 6 checkboxes inside it (below is my database)
checkboxlist1 : id , rowa
checkboxlist2:id , rowb
id : int
rowa : nvarchar(250)
rowb : nvarchar(250)
When I click one checkbox, the value is saved to my database as A1 , A2.... Here is my code:
Dim str1 As [String] = ""
For a As Integer = 0 To CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(a).Selected Then
If str1 = "" Then
str1 = CheckBoxList1.Items(a).Text
Else
str1 += "," + CheckBoxList1.Items(a).Text
str1 = ""
End If
End If
Next
For a1 As Integer = 0 To CheckBoxList1.Items.Count - 10
CheckBoxList1.Enabled = False
Next
Dim str2 As [String] = ""
For b As Integer = 0 To CheckBoxList2.Items.Count - 1
If CheckBoxList2.Items(b).Selected Then
If str2 = "" Then
str2 = CheckBoxList2.Items(b).Text
Else
str2 += "," + CheckBoxList2.Items(b).Text
End If
End If
Next
Dim connectionString As String =
ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim insertSql As String = "INSERT INTO tbtest(rowa,rowb)VALUES(#rowa,#rowb)"
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(insertSql, myConnection)
myCommand.Parameters.AddWithValue("#rowa", str1)
myCommand.Parameters.AddWithValue("#rowb", str2)
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
But somehow, when I load the page, it does not show the checked state
(checked/unchecked). Here is my code in page load. So my question is
?
How to show the checked state of checkboxlist ?
I try to save the state in session , but when i check a blank checkbox , it will then
save all the checked value to my database , how to avoid this ? i mean i want to save
only the value which is unchecked to database ?
If it is possible can you make the checked checkboxes disable ?
Page_load
Dim connectionString As String =
Using myConnection As New SqlConnection(connectionString)
Dim objCmd_team As SqlCommand = New SqlCommand("SELECT [rowa],[rowb] FROM [tbtest]", myConnection)
myConnection.Open()
Dim objReader As SqlDataReader = objCmd_team.ExecuteReader()
While (objReader.Read())
Dim currentCheckBox As ListItem = checkboxlist1.Items.FindByText(objReader("rowa"))
If currentCheckBox IsNot Nothing Then
currentCheckBox.Selected = True
End If Dim currentCheckBox1 As ListItem = checkboxlist2.Items.FindByText(objReader("rowb"))
If currentCheckBox1 IsNot Nothing Then
currentCheckBox1.Selected = True
End If End While End Using

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