I have an ASP.NET control that I have bound to a SQL result:
<asp:GridView ID="EmployeeSearchResults" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="Status" SortExpression="Status">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# (EmployeeSearchStatus(Eval("SeparationDate"),Eval("PositionTitle"),Eval("EffectiveDate"))) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My EmployeeSearchStatus function is very basic, testing the values passed in for NULL, and creating a string to display:
Public Function EmployeeSearchStatus(ByVal SeparationDate As Object, ByVal PositionTitle As Object, ByVal EffectiveDate As Object) As String
Dim ReturnString As String = ""
If IsDBNull(SeparationDate) Then
ReturnString = "Currently Employed as "
Else
ReturnString = "Last Employed as "
End If
ReturnString += PositionTitle
If IsDBNull(SeparationDate) Then
ReturnString += " (effective " + EffectiveDate + ")."
Else
ReturnString += " (separated on " + SeparationDate + ")."
End If
Return ReturnString
End Function
Is this the proper way to handle NULL values coming back from SQL to an ASP.NET control? Is there a better technique?
Thanks,
Russell
Your code looks fine, although you could possibly simplify it a bit if you wanted:
Public Function EmployeeSearchStatus(ByVal SeparationDate As Object, ByVal PositionTitle As Object, ByVal EffectiveDate As Object) As String
If IsDBNull(SeparationDate) Then
Return "Currently Employed as " + PositionTitle + " (effective " + EffectiveDate + ")."
Else
Return "Last Employed as " + PositionTitle + " (separated on " + SeparationDate + ")."
End If
End Function
The code does assume, however, that PositionTitle and EffectiveDate will never be null. If this is not enforced in the database, you could add some checks to the code to deal with these situations.
Related
How to integrate Replace in this Private Sub?
I need to replace all words "NONE" with "":
Private Sub UpdateSKU()
Dim str As String
str = Me.Combo216.Column(1) & Space(1) & Me.Combo224.Column(1) & Space(1)
Me.Text423.Value = str
End Sub
I have tried
Private Function NONE(a As String)
If InStr(a, "NONE") > 0 Then
MsgBox "Original: " & a & vbCrLf & "Adjusted: " & Replace(a, "NONE", "")
End If
End Function
But I can't get it to work.
A function should return a value...
Your function does not declare a return type, nor does it ever assign a return value.
Try this instead:
Private Function NONE(a As String) As String
NONE = Replace(a, "NONE", "")
End Function
Try this:
Private Sub UpdateSKU()
Dim Text As String
Text = Me.Combo216.Column(1) & Space(1) & Me.Combo224.Column(1) & Space(1)
Me.Text423.Value = Replace(Text, "NONE", "")
End Sub
Also, don't use common function names (Str) for variables, and do rename your controls to something meaningful.
I have a main form called (frmcarSearch) that displays table data called (tblCar).
The form contains three drop-down menu (cmbCar, cmbType, cmbGroup) that allow user to filter data and display them in a sub-form called (frmCarSub)
and there are three buttons to save the filtered data btnPrint, btnPDF, btnExcel.
The question is: How to write a code for each button so that the report displays (or save) the data in the sub-form according to the choice from each drop-down menu?
The code for each combo box:
Private Sub cmbCar_AfterUpdate()
Me.cmbGroup.Value = ""
Me.cmbType.Value = ""
Me.frmCarSub.SetFocus
Me.frmCarSub.Form.Filter = "[CarNum]= '" & [cmbCar] & "'"
Me.frmCarSub.Form.FilterOn = True
End Sub
Private Sub cmbType_AfterUpdate()
Me.cmbGroup.Value = ""
Me.cmbCar.Value = ""
Me.frmCarSub.SetFocus
Me.frmCarSub.Form.Filter = "[TypeName]='" & [cmbType] & "'"
Me.frmCarSub.Form.FilterOn = True
End Sub
Private Sub cmbGroup_AfterUpdate()
Me.cmbCar.Value = ""
Me.cmbType.Value = ""
Me.frmCarSub.SetFocus
Me.frmCarSub.Form.Filter = "[CarGroupName]= '" & [cmbGroup] & "'"
Me.frmCarSub.Form.FilterOn = True
End Sub
I used this code for btnPrint button
Private Sub btnPrint_Click()
If IsNull([cmbCar]) Then
DoCmd.OpenReport "rptCar", acViewPreview
Else
DoCmd.OpenReport "rptCar", acViewPreview, , "[CarNum]='" & [cmbCar] & "'"
End If
End Sub
But the problem with this code is that I have to use three buttons for the three menus and this is illogical.
Thank you.
You could define a function such as the following with the module for your form:
Function FilterString() As String
If Not IsNull(cmbCar) Then FilterString = " AND [CarNum]= '" & cmbCar & "'"
If Not IsNull(cmbType) Then FilterString = FilterString & " AND [TypeName]= '" & cmbType & "'"
If Not IsNull(cmbGroup) Then FilterString = FilterString & " AND [CarGroupName]= '" & cmbGroup & "'"
FilterString = Mid(FilterString, 6)
End Function
Then, define another function such as:
Function SetFilter()
Me.frmCarSub.SetFocus
Me.frmCarSub.Form.Filter = FilterString
Me.frmCarSub.Form.FilterOn = True
End Function
Then, the event handlers for each of your comboboxes become:
Private Sub cmbCar_AfterUpdate()
SetFilter
End Sub
Private Sub cmbType_AfterUpdate()
SetFilter
End Sub
Private Sub cmbGroup_AfterUpdate()
SetFilter
End Sub
Finally, the Print button event handler can become:
Private Sub btnPrint_Click()
If FilterString = vbNullString Then
DoCmd.OpenReport "rptCar", acViewPreview
Else
DoCmd.OpenReport "rptCar", acViewPreview, , FilterString
End If
End Sub
And the user also has the ability to filter by more than one field.
I have a class called Person which has the properties FirstName, LastName and MiddleName and I have a form-wide SortedDictionary(Of Integer, Person) called oPeople.
On Form_Load, I call a method that loads a list of 65 people. Right now this is hard-coded but eventually I'll be grabbing it from a database.
Once the form is loaded, I have a TextBox called txtSearchForName for the user to enter a search term and have the system look through oPeople filtering on LastName for a full or partial match (case insensitive).
Eventually I would like to be able to search for comparisons between FirstName, LastName and MiddleName (if there is one).
At this point all I want to do is loop through the results of the LINQ query and output them to the console window.
Here's the Person class:
Public Class Person
Private _fnm As String = String.Empty
Public Property FirstName() As String
Get
Return _fnm
End Get
Set(ByVal value As String)
_fnm = value.Trim
End Set
End Property
Private _lnm As String = String.Empty
Public Property LastName() As String
Get
Return _lnm
End Get
Set(ByVal value As String)
_lnm = value.Trim
End Set
End Property
Private _mnm As String = String.Empty
Public Property MiddleName() As String
Get
Return _mnm
End Get
Set(ByVal value As String)
_mnm = value.Trim
End Set
End Property
Public Sub New()
End Sub
Public Sub New(ByVal firstName As String,
ByVal lastName As String,
Optional ByVal middleName As String = "")
_fnm = firstName
_lnm = lastName
_mnm = middleName
End Sub
End Class
This is the method I'm using to add people. I'm adding 65 people but have cut the code down:
Private Sub FillPeopleDictionary()
Try
If oPeople.Count > 0 Then oPeople.Clear()
Dim oNewPerson As Person = Nothing
oNewPerson = New Person("Scarlett", "Johansson")
oPeople.Add(1, oNewPerson)
oNewPerson = New Person("Amy", "Adams")
oPeople.Add(2, oNewPerson)
oNewPerson = New Person("Jessica", "Biel")
oPeople.Add(3, oNewPerson)
Catch ex As Exception
MessageBox.Show(ex.Message, "Error [FillPeopleDictionary]", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
This is my LINQ statement followed by the output to console which is called when the user clicks a button:
Dim sSearchTerm As String = txtSearchForName.Text.Trim.ToLower
Dim queryResults = From person In oPeople
'Where SqlMethods.Like(person.Value.LastName.ToLower, "%" & sSearchTerm & "%")
'Where person.Value.LastName.ToLower.Contains("%" & sSearchTerm & "%")
Console.WriteLine("search term: " & sSearchTerm &
Environment.NewLine & Environment.NewLine &
"queryResults.Count: " & queryResults.Count.ToString &
Environment.NewLine)
For Each result In queryResults
If Not String.IsNullOrEmpty(result.Value.MiddleName) Then
Console.WriteLine(result.Key.ToString.PadLeft(2, "0") & ": " & result.Value.FirstName & " " & result.Value.MiddleName & " " & result.Value.LastName)
Else
Console.WriteLine(result.Key.ToString.PadLeft(2, "0") & ": " & result.Value.FirstName & " " & result.Value.LastName)
End If
Next
The LINQ statement works as it stands, with no conditions, so it loops through and correctly lists all of the people in the oPeople collection.
There are two Where clauses commented out below the initial queryResults statement. Those are the two ways I was trying to filter. One approach was to use .Contains and the other was to use .Like however neither works.
If the user was to type "mar", I would hope to get back a list of 6 people from the list of 65(case insensitive):
Meghan Markle
Margo Robbie
Kate Mara
Mary Elizabeth Winstead
Marian Rivera
Amy Smart
Now of course that is searching on FirstName and LastName. Right now I am just trying to get LastName to work. With only the LastName the list would only be:
Meghan Markle
Kate Mara
Amy Smart
Can anyone see what I am doing wrong here? Or should I scrap the idea of using LINQ with a SortedDictionary?
Change your Person class to include a PersonId and pass that through like oNewPerson = New Person(1, "Scarlett", "Johansson").
Change the oPeople to be a List(Of Person) so when adding it would look like this oPeople.Add(oNewPerson).
Your LINQ statement would then look like this:
Dim queryResults = From person In oPeople
Where person.FirstName.ToLower Like "*" & sSearchTerm & "*" Or
person.LastName.ToLower Like "*" & sSearchTerm & "*"
You would also want to change the rest as no longer using a dictionary:
For Each result In queryResults
If Not String.IsNullOrEmpty(result.MiddleName) Then
Console.WriteLine(result.PersonId.ToString.PadLeft(2, CChar("0")) & ": " & result.FirstName & " " & result.MiddleName & " " & result.LastName)
Else
Console.WriteLine(result.PersonId.ToString.PadLeft(2, CChar("0")) & ": " & result.FirstName & " " & result.LastName)
End If
Next
Hope this helps.
Your 2nd Where clause attempt is close, except the Contains function there is String.Contains which does not use the % wildcard characters that SQL uses, so you need:
Dim queryResults =
From person In oPeople
Where person.Value.LastName.ToLower.Contains(sSearchTerm)
You can easily add a check for FirstName with OrElse person.Value.FirstName.ToLower.Contains(sSearchTerm).
Change your Linq query to be as follows:
Dim queryResults = From p In oPeople
Where p.Value.FirstName.ToLower.Contains(sSearchTerm) Or p.Value.LastName.ToLower.Contains(sSearchTerm)
Private Sub CBFRANK_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CBFRANK.CheckedChanged
If CBFRANK.Checked = True Then
existsub = subjectBox.Text
rollingsub = existsub + "FR, "
existfull = FullName.Text
rollingfull = existfull + "Franklin Hospital, "
subjectBox.Text = rollingsub
FullName.Text = rollingfull
Else
Replace(FullName.Text, "Franklin Hospital, ", "")
End If
End Sub
Thats what I have, and what it does is basically when you check a box it adds "ZHH, " to one text box and "Zucker Hillside Hospital, " to another.
What I want to be able to do is search those text boxes when the property is unchecked and I want it to just remove those additions regardless of where they are
So imagine I have this in the respective boxes:
XXX, ZHH, XXX
And in the other box
XXX Hospital, Zucker Hillside Hospital, XXX Hospital
I want to be able to remove both ZHH and Zucker Hillside Hospital from their respective boxes regardless of where they are in the string
The event handler would be the unchecked function the other "if"
Just use String.Replace searching for the text to remove and setting an empty string in its place
Private Sub CBZUCK_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CBZUCK.CheckedChanged
If CBZUCK.Checked = True Then
subjectBox.Text = subjectBox.Text & "ZHH, "
FullName.Text = FullName.Text & "Zucker Hillside Hospital, "
Else
subjectBox.Text = subjectBox.Text.Replace("ZHH, ", "")
FullName.Text = FullName.Text.Replace("Zucker Hillside Hospital, ", "")
End If
End Sub
You can use the function Replace(), like this
replace(myString,"ZHH","")
so it's replace every instance of ZHH bu nothing.
Beware that it can erase ZHHYTVF and leave YTVF. It might not want that.
If CBZUCK.Checked = True Then
subjectBox.Text = subjectBox.Text & "ZHH, "
FullName.Text = FullName.Text & "Zucker Hillside Hospital, "
Else
subjectBox.Text = subjectBox.Text.Replace("ZHH, ", "")
FullName.Text = FullName.Text.Replace("Zucker Hillside Hospital, ", "")
End If
End Sub
Thank you!
I have created a button to add the fields in a a textbox and I wanted to pass the textbox name as parameter in a sub,which inturn inserts into the database..How can i do it..pls find my code for reference below in vb.net
The code for inserting the values in database
Sub Add_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim addedButton As Button = sender
Dim sqlcmd As SqlCommand
Dim insertdata As String
addedButton.Text = "Added"
adduser = True
addedButton.Enabled = True
If (cname.Value = " " Or cid.Value = " " Or cadd.Value = " " Or cph.Value = " " Or fax.Value = " " Or cmail.Value = " ") Then
Message.InnerHtml = "ERROR: Null values not allowed for " _
& "Client ID, Name"
Message.Style("color") = "red"
BindGrid()
Else
Message.InnerHtml = "<b>Client Record has been added</b><br/>"
End If
insertdata = "INSERT INTO dbo.ClientInfo([Client Name],[Client ID],[Client Address],[Client Telephone No],[Client Fax No],[Client E-mail]) values("
insertdata = insertdata + " ' " + cname.Value + " '," + cid.Value + ",' " + cadd.Value + " '," + cph.Value + "," + fax.Value + "," + cmail.Value
sqlcmd = New SqlCommand(insertdata, sqlcon)
Try
sqlcmd.Connection.Open()
Dim addcount As Integer = sqlcmd.ExecuteNonQuery()
If addcount > 0 Then
Message.InnerHtml = "Record successfully Added"
Else
Message.InnerHtml = "Record not added"
End If
Catch ex As SqlException
If ex.Number = 2627 Then
Message.InnerHtml = "ERROR: A record already exists with " _
& "the same primary key"
End If
Finally
sqlcmd.Connection.Close()
BindGrid()
End Try
End Sub
<asp:Button id="Button1"
Text="Add data"
OnClick="Add_Click"
runat="server"/><br />
Name:<input type ="text" id="cname" name="" value="" runat="server"/><br />
ID: <input type = "text" id="cid" name="txtclientid" value="" runat="server"/><br />
Address:<input type="text" id="cadd" name="txtclientadd" value="" runat="server"/><br />
Phone No:<input type="text" id="cph" name="txtno" value="" runat="server" /><br />
Fax No:<input type="text" id="fax" name="faxno" value="" runat="server"/><br />
E-mail:<input type="text" id="cmail" name="mail" value="" runat="server"/><br />
<input type="reset" name="reset" value="Clear" /><br />
Not exactly what you asked for, but closer to what you should be doing:
Public Sub InsertClientInfo(ByVal ClientName As String, ByVal ClientID As Integer, ByVal ClientAddress As String, ByVal ClientPhone As String, ByVal ClientFax As String, ByVal ClientEmail As String)
Dim sql As String = _
"INSERT INTO ClientInfo (" & _
"[Client Name],[Client ID],[Client Address],[Client Telephone No],[Client Fax No],[Client E-mail]" & _
") VALUES (" & _
"#ClientName, #ClientID, #ClientAddress, #ClientPhone, #ClientFax, #ClientEmail)"
Using cn As New SqlConnection("connection string"), _
cmd As New SqlCommand(sql, cn)
'I had to guess at the column types and lengths here. Adjust accordingly
cmd.Parameters.Add("#ClientName", SqlDbType.NVarChar, 50).Value = ClientName
cmd.Parameters.Add("#ClientID", SqlDbType.Int).Value = ClientID
cmd.Parameters.Add("#ClientAddress", SqlDbType.NVarChar, 200).Value = ClientAddress
cmd.Parameters.Add("#ClientPhone", SqlDbType.NVarChar, 16).Value = ClientPhone
cmd.Parameters.Add("#ClientFax", SqlDbType.NVarChar, 16).Value = ClientFax
cmd.Parameters.Add("#ClientEmail", SqlDbType.NVarChar, 50).Value = ClientEmail
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Note that I had to guess at data types and sizes. You need to fix that to make your actual table definitions. Call it like this:
InsertClientInfo(textname.Text, Convert.ToInt32(textclientid.Text), txtclientadd.Text, txtno.Text, faxno.Text, mail.Text)
To pass the TEXTBOX name to any sub do as follows,
Sub SomeSubName(ThisTextboxName as string)
'your code here
End Sub
or to a function
Function SomeFunctionName(ThisTextBoxName as String) As Boolean
'your code here
End Function
Where...
SomeSubName and SomeFunctionName are the names of your sub or function
ThisTextBoxName is the variable name of the STRING data which is the actual textbox name
So if your textbox is named txtPhone Then you would pass it as....
SomeSubName(txtPhone.Name)
or
Dim Test as Boolean
Test = SomeFunctionName(txtPhone.Name)