The select command property has not been initialized before calling 'Fill' - vb.net

I am working on a Windows forms project that connects to a Microsoft Access database, reads the the file, does some math and then provides some basic statistics back. Right now I am teaching myself VB and I know the code below could be more efficient. However, right now I am just trying to make it functional.
The program filters the data it needs via sql, and there are several sql statements. I separated the code for each of the sql statements and into a subroutine so that I could call each one when the form loads and also when the user clicks a button to update. The program works fine on the form load, however, when you click the update button you get the following error on the 'odaCalls.Fill' in subroutine Count(): "The select command property has not been initialized before calling 'Fill'.
Any help is greatly appreciated. I have searched on google and tried the suggestions found there but have not found a fix.
Option Explicit On
Public Class Form1
'Count() Variables
Dim strSQL = "SELECT * FROM tblcallLog"
Dim strPath As String = "Provider=Microsoft.ACE.OLEDB.12.0 ;" _
& "Data Source=C:\callLogRev2_be.accdb"
Dim odaCalls As New OleDb.OleDbDataAdapter(strSQL, strPath)
Dim datCallCount As New DataTable
Dim intCount As Integer = 0
'LiveCalls() variables
Dim strSQLLive As String = "SELECT * FROM tblcallLog WHERE callLive=True"
Dim odaCallsLive As New OleDb.OleDbDataAdapter(strSQLLive, strPath)
Dim datCallLive As New DataTable
Dim intCallLiveCount As Integer = 0
Dim decCallLivePct As Decimal
'TransferCalls() variables
Dim strSQLTransfered As String = _
"SELECT * FROM tblcallLog WHERE callName LIKE '% transfer %' OR callName LIKE 'transfer%'"
Dim odaCallsTransfered As New OleDb.OleDbDataAdapter(strSQLTransfered, strPath)
Dim datCallTransfered As New DataTable
Dim intCallTransfered As Integer = 0
Dim decCallTranfered As Decimal
'SingleStaffCall() Variables
Dim strSQLSingleStaff As String = _
"SELECT * FROM tblcallLog WHERE callName LIKE '% single %' OR callName LIKE 'single%'"
Dim odaCallSingleStaff As New OleDb.OleDbDataAdapter(strSQLSingleStaff, strPath)
Dim datCallSingleStaff As New DataTable
Dim intCallSingleStaff As Integer = 0
Dim decCallSingleStaff As Decimal
'SingleStaffCallsLive() Variables
Dim strSQLSingleStaffLive As String = _
"SELECT * FROM tblcallLog WHERE callName LIKE '% single %' OR callName LIKE 'single%' AND callLive=True"
Dim odaCallSingleStaffLive As New OleDb.OleDbDataAdapter(strSQLSingleStaffLive, strPath)
Dim datCallSingleStaffLive As New DataTable
Dim intCallSingleStaffLive As Integer = 0
Dim decCallSingleStaffLive As Decimal
'CallToday() Variables
Dim strSQLToday As String = _
"SELECT * FROM tblcallLog WHERE startDate = date()"
Dim odaCallToday As New OleDb.OleDbDataAdapter(strSQLToday, strPath)
Dim datCallToday As New DataTable
Dim intCallToday As New Integer
'CallTodayLive() Variables
Dim strSQLTodayLiveCalls As String = _
"SELECT * FROM tblcallLog WHERE callLive=TRUE AND startDate = date()"
Dim odaCallTodayLive As New OleDb.OleDbDataAdapter(strSQLTodayLiveCalls, strPath)
Dim datCallTodayLive As New DataTable
Dim intCallTodayLive As New Integer
Dim decCallTodayLive As New Decimal
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Count()
LiveCalls()
TransferCalls()
SingleStaffCalls()
SingleStaffCallsLive()
CallToday()
CallTodayLive()
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
'Checks the database for updates when user pushes the update button on the static data tab.
Count()
LiveCalls()
TransferCalls()
SingleStaffCalls()
SingleStaffCallsLive()
CallToday()
CallTodayLive()
End Sub
Private Sub Count()
'database connect and call count
odaCalls.Fill(datCallCount)
odaCalls.Dispose()
intCount = datCallCount.Rows.Count
lblTotalCallsData.Text = intCount.ToString
lblTotalCallsData.Visible = True
End Sub
Private Sub LiveCalls()
'determine number of live calls
odaCallsLive.Fill(datCallLive)
odaCallsLive.Dispose()
intCallLiveCount = datCallLive.Rows.Count
lblcallsLiveData.Text = intCallLiveCount.ToString
lblcallsLiveData.Visible = True
decCallLivePct = intCallLiveCount / intCount
lblPctCallsLiveData.Text = decCallLivePct.ToString("P")
lblPctCallsLiveData.Visible = True
End Sub
Private Sub TransferCalls()
'determine the number of transfer calls
odaCallsTransfered.Fill(datCallTransfered)
odaCallsTransfered.Dispose()
intCallTransfered = datCallTransfered.Rows.Count
lblTotalTransferCallsData.Text = intCallTransfered.ToString
lblTotalTransferCallsData.Visible = True
decCallTranfered = intCallTransfered / intCount
lblPctTransferCallsData.Text = decCallTranfered.ToString("P")
lblPctTransferCallsData.Visible = True
End Sub
Private Sub SingleStaffCalls()
'determine the number of single staff calls and percentage of total
odaCallSingleStaff.Fill(datCallSingleStaff)
odaCallSingleStaff.Dispose()
intCallSingleStaff = datCallSingleStaff.Rows.Count
lblTotalSingleStaffCallData.Text = intCallSingleStaff.ToString
lblTotalSingleStaffCallData.Visible = True
decCallSingleStaff = intCallSingleStaff / intCount
lblPctSingleStaffCallsData.Text = decCallSingleStaff.ToString("P")
End Sub
Private Sub SingleStaffCallsLive()
'determine the percentage of single staff calls taken live
odaCallSingleStaffLive.Fill(datCallSingleStaffLive)
odaCallSingleStaffLive.Dispose()
intCallSingleStaffLive = datCallSingleStaffLive.Rows.Count
decCallSingleStaffLive = intCallSingleStaffLive / intCount
lblPctSingleStaffCallsLiveData.Visible = True
lblPctSingleStaffCallsLiveData.Text = decCallSingleStaffLive.ToString("P")
End Sub
Private Sub CallToday()
'determine values for todays date
odaCallToday.Fill(datCallToday)
odaCallToday.Dispose()
intCallToday = datCallToday.Rows.Count
lblTotalCallsTodayData.Text = intCallToday
lblTotalCallsTodayData.Visible = True
End Sub
Private Sub CallTodayLive()
'determine the number of live calls today
odaCallTodayLive.Fill(datCallTodayLive)
odaCallTodayLive.Dispose()
intCallTodayLive = datCallTodayLive.Rows.Count
lblCallsTodayLiveData.Text = intCallTodayLive.ToString
lblCallsTodayLiveData.Visible = True
'Statement to error correct so the database doesn't force the program to divide by zero
Try
decCallTodayLive = intCallTodayLive / intCallToday
Catch Exception As DivideByZeroException
lblPctCallsTodayLiveData.Text = "0.00%"
lblPctCallsTodayLiveData.Visible = True
Catch Exception As OverflowException
decCallTodayLive = 0
End Try
lblPctCallsTodayLiveData.Text = decCallTodayLive.ToString("P")
lblPctCallsTodayLiveData.Visible = True
End Sub
End Class

The problem is that you are disposing the dataadapters immediately after filling them.
This is why it works on form load, but not after. It would be better practice to create the and destroy the dataadapters in the methods where they are used instead of creating them on spec at the form level.

Related

Can't display Data in ComboBox Control of DropDownStyle (DropDownList)

I have the following requirement,
I have a ComboBox Control (DropDownList Style) which user has to select a given value, but can not edit. Then I save it to a Database Table, and it's working fine.
(dataRow("it_discount_profile") = Trim(cmbDisProfile.Text))
But when I try to show the same Data in the same ComboBox by retrieving it from the Database, it won't show.
(cmbDisProfile.Text = Trim(tempTb.Rows(0).Item("it_discount_profile")))
When I change the ComboBox to "DropDown Style", it works. But then the User can edit it.
Am I missing something here or is it like that? Any advice will be highly appreciated.
Im filling it in runtime using a procedure.
Private Sub filldisProfiles()
Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
cmbDisProfile.DataSource = tempTb
cmbDisProfile.DisplayMember = "discount_profile"
End Sub
Ok. Actually, Im trying to migrate one of my old project from VB to VB.Net. VB.Net is little new to me. Im using a self built classto reduce codes in other places. Im attaching the class below.
My actual requirement is to populate the combo box from a table. I like to do it in run time. I don't want users to edit it. If they want to add a new value, they have separate place (Form) for that. I think im doing it in a wrong way. If possible please give a sample code since I'm not familiar with the proposed method.
Public Function myFunctionFetchTbData(ByVal inputSqlString As String) As DataTable
Try
Dim SqlCmd As New SqlCommand(inputSqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim fetchedDataSet As New DataSet
fetchedDataSet.Clear()
dataAdapter.Fill(fetchedDataSet)
Dim fetchedDataTable As DataTable = fetchedDataSet.Tables(0)
Return fetchedDataTable
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
' this sub will update a table
Public Sub MyMethodUpdateTable(ByVal sqlString As String, ByVal tbToUpdate As DataTable)
Dim SqlCmd As New SqlCommand(sqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim objCommandBuilder As New SqlClient.SqlCommandBuilder(dataAdapter)
dataAdapter.Update(tbToUpdate)
End Sub
Public Function MyMethodfindRecord(ByVal strSearckKey As String, ByVal tableName As String, ByVal strColumnName As String) As Boolean
Try
Dim searchSql As String = "SELECT * FROM " & tableName & " WHERE " & strColumnName & "='" & strSearckKey & "'"
'Dim searchString As String = txtCategoryCode.Text
' searchOwnerCmd.Parameters.Clear()
' searchOwnerCmd.Parameters.AddWithValue("a", "%" & search & "%")
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(searchSql)
If tempTb.Rows.Count = 0 Then
Return False
Else
Return True
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
Public Function myFunctionFetchSearchTB(ByVal inputSqlString As String) As DataTable
Try
Dim SqlCmd As New SqlCommand(inputSqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim fetchedDataSet As New DataSet
fetchedDataSet.Clear()
dataAdapter.Fill(fetchedDataSet)
Dim fetchedSearchTB As DataTable = fetchedDataSet.Tables(0)
Return fetchedSearchTB
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
OK. If I understood correctly, you have a problem in retrieving Data [String] from a Database Table into a ComboBox of DropDownStyle [DropDownList].
How do you fill/populate your ComboBox with Data From Database Table ?
In this link, Microsoft docs state, that:
Use the SelectedIndex property to programmatically determine the index
of the item selected by the user from the DropDownList control. The
index can then be used to retrieve the selected item from the Items
collection of the control.
In much more plain English
You can never SET ComboBox.Text Value while in DropDownList by code, which you already knew by testing your code, but you need to use DisplayMember and ValueMember or SelectedIndex.
ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
Please consider populating your ComboBox Control from Database Table using (Key,Value) Dictionary collection, here is an example
Thank you guys for all the advice's. The only way it can be done is the way u said. I thought of putting the working code and some points for the benefit of all.
proposed,
ComboBox1.SelectedIndex = comboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))"
does not work when u bind the datatable to the combobox. The values should be added to the combo box in run time if the above "SelectedIndex" method to work. The code to add items to the combobox is as follows(myClassTableActivities is a class defined by myself and its shown above),
Private Sub filldisProfiles()
Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
Dim i As Integer = 0
For i = 0 To tempTb.Rows.Count - 1
cmbDisProfile.Items.Add(Trim(tempTb.Rows(i).Item("discount_profile")))
Next
End Sub
After adding we can use the following code to display the data on combobox (DropDownList).
Private Sub txtItCode_TextChanged(sender As Object, e As EventArgs) Handles txtItCode.TextChanged
Try
Dim sqlString As String = "SELECT * FROM tb_items where it_code='" & Trim(txtItCode.Text) & "'"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
If Len(txtItCode.Text) < 4 Then
cmdAdd.Enabled = False
cmdDelete.Enabled = False
cmdSave.Enabled = False
Else
If tempTb.Rows.Count > 0 Then
With tempTb
txtItName.Text = Trim(tempTb.Rows(0).Item("it_name"))
cmbDisProfile.SelectedIndex = cmbDisProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
cmbProfitProfile.SelectedIndex = cmbProfitProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_profit_profile")))
cmbItCategory.SelectedIndex = cmbItCategory.FindStringExact(Trim(tempTb.Rows(0).Item("it_category")))
cmbFinanCategory.SelectedIndex = cmbFinanCategory.FindStringExact((tempTb.Rows(0).Item("it_finance_category")))
End With
cmdAdd.Enabled = False
cmdDelete.Enabled = True
cmdSave.Enabled = True
Else
cmdAdd.Enabled = True
cmdDelete.Enabled = False
cmdSave.Enabled = False
txtItName.Text = ""
Call fillItCategories()
Call fillProProfile()
Call filldisProfiles()
Call fillFinCat()
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try

vb.net threading sub slower than call sub

I know this Question was already posted, but it was never really answered, or I did not understand the answer :)
My Problem is that when I call this Sub within the Thread, it takes about 4 sec to execute the code, but if I make a simple Call Sub (Like commented in Code) it takes about 450 ms.
I have a simple program with 2 Subs:
To report Progress on Main Form
To do some "For" Looping
Imports System.Data.SqlClient
Public Class Form1
Public Delegate Sub ProzentDelegate(ByVal Prozent As Double)
Dim G_I_Temp As Integer = 0
Dim G_S_Prüfziffer As String
Dim G_S_Präfix As String
Dim G_I_Zähler As Integer
Dim G_I_Stellen As Integer
Dim G_D_Step As Integer = 1
Dim G_I_Position As Integer
Dim DT_G_Prüftabelle As DataTable
Dim DR_G_Prüftabelle As DataRow
Dim thisLock As New Object
Dim conn As String = "Data Source=SR-SQLWVS;Initial Catalog=Barcode;Integrated Security=True"
Dim sourceconn As New SqlConnection(conn)
Dim adap As SqlDataAdapter
Dim cmd As SqlCommand = New SqlCommand("SELECT TOP(10) * FROM dbo.Prüf_Tabelle", sourceconn)
Dim Thrd_preview As Threading.Thread
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sourceconn.Open()
cmd.Connection = sourceconn
End Sub
Public Sub ReportProgress(ByVal Prozent As Double)
ProgressBar1.Value = Prozent
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If RB_Thread.Checked Then
If Thrd_preview IsNot Nothing Then Thrd_preview = Nothing
Thrd_preview = New Threading.Thread(AddressOf DoSomeWork)
Thrd_preview.IsBackground = True
Thrd_preview.Start()
Else
DoSomeWork()
End If
End Sub
Private Sub DoSomeWork()
Dim ds As New DataSet
DT_G_Prüftabelle = ds.Tables.Add("Prüf_Tabelle")
Dim L_I_Counter, L_I_Counter2 As Integer
Dim L_I_Ende As Integer
Dim L_I_Step As Integer
Dim L_I_Nutzen As Integer = 1
L_I_Step = 1
L_I_Ende = Val(TB_Auftrag_neu_Anzahl.Text)
G_I_Stellen = 8
G_S_Prüfziffer = "1"
G_S_Präfix = "00"
If TB_Info_Increment.Text = "" Then TB_Info_Increment.Text = 1
adap = New SqlDataAdapter("SELECT TOP(10) * FROM dbo.Prüf_Tabelle", sourceconn)
adap.FillSchema(DT_G_Prüftabelle, SchemaType.Mapped)
DT_G_Prüftabelle.Rows.Clear()
Dim pre As Date = Now
For L_I_Counter = 1 To (L_I_Ende * L_I_Step) Step L_I_Step
For L_I_Counter2 = 1 To L_I_Nutzen
DR_G_Prüftabelle = DT_G_Prüftabelle.NewRow
DR_G_Prüftabelle.Item("Auftrag_Lfd_nr") = TB_KeyLot.Text
DR_G_Prüftabelle.Item("Position") = G_I_Position
G_I_Position += G_D_Step
DR_G_Prüftabelle.Item("Barcode_soll") = F_Berechnung((Trim(Str(Val(TB_Auftrag_neu_Von.Text) + L_I_Counter - 1))).PadLeft(G_I_Stellen, "0"))
DT_G_Prüftabelle.Rows.Add(DR_G_Prüftabelle)
If ProgressBar1.InvokeRequired Then
ProgressBar1.BeginInvoke(New ProzentDelegate(AddressOf ReportProgress), (L_I_Counter * 100) / (L_I_Ende * L_I_Step))
Else
ReportProgress((L_I_Counter * 100) / (L_I_Ende * L_I_Step))
End If
Next
Next
MsgBox(Now.Subtract(pre).TotalMilliseconds.ToString & " ms.")
End Sub
Function F_Berechnung(ByVal L_Nummer As String) As String
Dim L_B_Gerade As Boolean = False
Dim L_I_Prüfziffer As Integer
Dim L_I_Stellen As Integer
Me.G_I_Temp = 0
Select Case G_S_Prüfziffer
Case "0"
F_Berechnung = L_Nummer
Case "1"
F_Berechnung = G_S_Präfix & Trim(L_Nummer)
Case "2"
F_Berechnung = G_S_Präfix & Trim(L_Nummer)
Case "3"
F_Berechnung = L_Nummer
'
Case "5" '-----Mod 10 gewichtung 31...-----
L_Nummer = G_S_Präfix & Trim(L_Nummer)
L_I_Stellen = Len(L_Nummer)
For Me.G_I_Zähler = L_I_Stellen To 1 Step -1
Me.G_I_Temp += Val(Mid(L_Nummer, Me.G_I_Zähler, 1)) * IIf(L_B_Gerade, 1, 3)
L_B_Gerade = Not L_B_Gerade
Next
L_I_Prüfziffer = IIf(10 - Me.G_I_Temp Mod 10 = 10, 0, 10 - Me.G_I_Temp Mod 10)
F_Berechnung = Trim(L_Nummer) & Trim(Str(L_I_Prüfziffer))
'
Case "6" '-----Mod 10 gewichtung 13...-----
L_Nummer = G_S_Präfix & Trim(L_Nummer)
L_I_Stellen = Len(L_Nummer)
For Me.G_I_Zähler = L_I_Stellen To 1 Step -1
Me.G_I_Temp += Val(Mid(L_Nummer, Me.G_I_Zähler, 1)) * IIf(L_B_Gerade, 3, 1)
L_B_Gerade = Not L_B_Gerade
Next
L_I_Prüfziffer = IIf(10 - Me.G_I_Temp Mod 10 = 10, 0, 10 - Me.G_I_Temp Mod 10)
F_Berechnung = Trim(L_Nummer) & Trim(Str(L_I_Prüfziffer))
'
Case Else
F_Berechnung = L_Nummer
End Select
End Function
I have tried to take out Progress Reporting but the Result is the same.
I hope you have some suggestions or solutions for me. I would be very thankful.
Give these changes a try
Change this
If ProgressBar1.InvokeRequired Then
ProgressBar1.Invoke(New ProzentDelegate(AddressOf ReportProgress), Progr)
Else
ReportProgress(Progr)
End If
to
ReportProgress(Progr)
And change method ReportProgress to
Public Sub ReportProgress(ByVal Prozent As Double)
Me.BeginInvoke(Sub()
ProgressBar1.Value = Prozent
End Sub)
End Sub
See if that makes a difference. The check for InvokeRequired is not needed, the answer is always yes.
Just wanted to report that I found a solution.
The main problem was this line of code in:
DR_G_Prüftabelle.Item("Auftrag_Lfd_nr") = TB_KeyLot.Text
So if I start this Sub from another Thread rather than from a Main Thread, for every single loop it has to go to main thread and to take Paramater from TextBox and to go back in Thread to Loop further.
I took that out, declared a variable at the begining and assigned this TextBox value to it and it works like charm.
Also I took a suggestion from dbasnett to Invoke Reporting every time without If-Else and also the suggestion from Steven Doggart to Report every 100 Loops.
You guys helped a lot. Thanks for that!!

Query in VB.net sometimes doesn't work

I have a functionality which saves the information from a webform to the database, which is working fine.
This is my code for save functionality in Onspec.aspx.vb page
Public Sub SaveClick(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsValid Then
litMessage.Text = ""
Exit Sub
End If
Try
Dim sName As String = ""
With EmployerCandidate
.employerid = Master.Employer.ID
.employeruserid = 0
Try
.CVID = DocId
Catch
End Try
.Name = uxName.Text
.SurName = uxSurname.Text
Try
.PostCode = uxPostcode.Text
Catch ex As Exception
End Try
.Email = uxEmail.Text
Try
.MobileNo = uxMobileNo.Text
Catch ex As Exception
End Try
.OnSpec = True
.OnSpecType = uxOnSpecCategory.SelectedItem.Text
.Source = uxSourceID.SelectedItem.Text
.LastEmployer = uxEmployer.Text
.LastJobTitle = uxJobtitle.Text
.Profile = uxProfile.Text.Trim
End With
' email()
ResetForm()
panForm.Visible = False
panUpload.Visible = True
uxSubmit.Visible = False
uxUpload.Visible = True
litMessage.Text = "Thank you for submitting your details! We'll be in touch when appropriate vacancy arises. <a href='#' onclick='parent.$.colorbox.close()'>Close</a>"
UploadPanel.Visible = False
Response.Redirect("onspec-complete.aspx?e=" & Master.Employer.ID)
Catch ex As Exception
litMessage.Text = Core.Helper.FancyMessage("Error as occurred - " & ex.Message.ToString, "ERROR")
End Try
End Sub
Now, I want to send emails along with saving the data in the database so I added the following lines of code before ResetForm().
Dim specmatch As DataRow = DB.GetRow("SELECT TOP 1 name,email,password FROM [user] usr JOIN employeruser empUsr ON usr.id = empUsr.userid WHERE empUsr.empusertype = 1 AND empUsr.employerid = #eid ", DB.SIP("eid", LocalHelper.UserEmployerID))
If my query returns a value then I want to send email by calling the email function.
If specmatch IsNot Nothing Then
email()
End If
But in this line of code the employerid value is sometimes empty. It can't pick the id therefore it is returning an empty row. And therefore it's not calling the email function.
This id is the same as
.employerid = Master.Employer.ID
But if I replace the LocalHelper.UserEmployerID with Master.Employer.ID the form gives an error:
Object reference not set to an instance of an object.
employerid is an integer value.
I have also tried to add the following lines of code in this page(Onspec.aspx.vb)
Public ReadOnly Property EmployerId() As Integer
Get
Return Master.Employer.ID
End Get
End Property
But I get the same error:
Object reference not set to an instance of an object.
The above lines of code does not make any difference.
So I replaced Master.Employer.ID with LocalHelper.UserEmployerID
Where in localhelper.vb file (under appcode folder) it is determining employerid from the website with following lines of code.
Public Shared Function UserEmployerID() As Integer
If HttpContext.Current.Items("lh_useremployerid") Is Nothing Then
If LocalHelper.UserTypeCode = "e" Then
HttpContext.Current.Items("lh_useremployerid") = Core.DB.GetInteger("SELECT employerid FROM employeruser WHERE userid = " & LocalHelper.UserID)
Else
HttpContext.Current.Items("lh_useremployerid") = 0
End If
End If
Return HttpContext.Current.Items("lh_useremployerid")
End Function
These lines of code has been used in many places and works perfectly fine. In this case as well, it was working fine last Friday and now it's not. There was no changes made.
This is my email function
Private Sub email()
Dim strCandidateName As String = uxName.Text.Trim & " " & uxSurname.Text.Trim
Dim strCandidateSurname As String = uxSurname.Text
Dim strCandidateEmail As String = uxEmail.Text.Trim
Dim strCandidatePhone As String = uxMobileNo.Text.Trim
Dim strCPass As String = "mpb123"
Dim strContactType As String = "Speculative Application has been submited on the category of " & uxOnSpecCategory.SelectedItem.Text
Dim strContactMessage As String = uxProfile.Text.Trim
'''''''''''''''''''variable
Dim qq As String = String.Format("Select top 1 name, email, password FROM [user] WHERE id in (Select userid FROM employeruser WHERE empusertype=1 and employerid= " & LocalHelper.UserEmployerID & ")")
Dim drow As DataRow = Core.DB.GetRow(qq)
Dim semail As String = drow.Item("email").ToString
Dim sname As String = drow.Item("name").ToString
Dim spass As String = drow.Item("password").ToString
'''''''''''''''''''variable
Dim Email As Core.Email
'New Onspec Candidate Email sent to EmployerUser who is assigned to receive onspec email
Email = New Core.Email
With Email
.ContentID = 99
.Replacement("ContactName", strCandidateName)
.Replacement("ContactEmail", strCandidateEmail)
.Replacement("ContactTelephone", strCandidatePhone)
.Replacement("ContactType", strContactType)
.Replacement("ContactMessage", strContactMessage)
.Replacement("AdminContactName", sname)
.Replacement("AdminContactEmail", semail)
.Replacement("SiteName", LocalHelper.AppSetting("sitename"))
Dim attachments As New Generic.List(Of String)
If EmployerCandidate.CVID > 0 Then
Dim doc As New Document(EmployerCandidate.CVID)
attachments.Add(doc.PathOnDisc)
End If
.Attachments = Join(attachments.ToArray(), ";")
.Send()
End With
End Sub
GetRow function is defined in my database.vb page like following which is also used in many other places.
Shared Function GetRow(ByVal selectQueryText As String, ByVal ParamArray params As SqlParameter()) As DataRow
Return GetRowFromDB(selectQueryText, CommandType.Text, params)
End Function
And
Shared Function GetRowFromDB(ByVal selectCommandText As String, ByVal selectCommandType As CommandType, ByVal ParamArray params As SqlParameter()) As DataRow
Dim conn As SqlConnection = Nothing
Try
conn = GetOpenSqlConnection()
Return GetRowFromDB(conn, selectCommandText, selectCommandType, params)
Finally
If conn IsNot Nothing Then conn.Dispose()
End Try
End Function
Please suggest ways on how I can organize my code so that it works all the time.

DataGridView not Refreshing

I have a SQL table that looks similar to this:
1 | a | stuff...
2 | a | stuff...
3 | b | stuff...
4 | a | stuff...
5 | b | stuff...
I only want to show:
3 | b | stuff...
5 | b | stuff...
So I use this code to load the DataGridView:
Private Sub GetData()
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
' Create an instance of a DataAdapter.
Dim daInstTbl As _
New SqlDataAdapter("SELECT * FROM Table WHERE Column = 'b'", objConn)
' Create an instance of a DataSet, and retrieve data from the Authors table.
daInstTbl.FillSchema(dsNewInst, SchemaType.Source)
daInstTbl.Fill(dsNewInst)
' Create a new instance of a DataTable
MyDataTable = dsNewInst.Tables(0)
daInstTbl.Update(dsNewInst)
End Sub
Private Sub InitializeDataGridView()
Try
' Set up the DataGridView.
With Me.DataGridView1
' Set up the data source.
.DataSource = MyDataTable
End With
Catch ex As SqlException
MessageBox.Show(ex.ToString, _
"ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
System.Threading.Thread.CurrentThread.Abort()
End Try
End Sub
Everything works great and until I want to delete 3 and renumber 4 and 5 down one to become 3 and 4. I have loops handling everything and the database is receiving the correct data except my DataGridView only shows the updates when I restart the program.
Here's my delete code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim daInstDeleteTbl As New SqlDataAdapter("SELECT * FROM Table", objConn)
Dim dsDeleteInst As New DataSet
Dim MyDeleteTable As DataTable
' Create an instance of a DataSet, and retrieve data from the Authors table.
daInstDeleteTbl.FillSchema(dsDeleteInst, SchemaType.Source)
daInstDeleteTbl.Fill(dsDeleteInst)
' Create a new instance of a DataTable
MyDeleteTable = dsDeleteInst.Tables(0)
'Begin Delete Code
Dim DeleteID, DeleteIndex As Integer
Dim MadeChange As Boolean = False
Integer.TryParse(TextBox1.Text, DeleteID)
Dim dgvIndexCount As Integer = MyDeleteTable.Rows.Count - 1
If MyDeleteTable.Rows(dgvIndexCount).Item(0) > DeleteID Then
Dim counter As Integer = -1
For Each row As DataRow In MyDeleteTable.Rows
counter += 1
If row.Item("Column") = DeleteID Then
DeleteIndex = counter
End If
Next
MadeChange = True
End If
drCurrent = MyDeleteTable.Rows.Find(DeleteID)
drCurrent.Delete()
If MadeChange = True Then
Dim i As Integer = 0
For i = DeleteIndex + 1 To dgvIndexCount
MyDeleteTable.Rows(i).Item(0) = MyDeleteTable.Rows(i).Item(0) - 1
Next
End If
'Send Changes to SQL Server
Dim objCommandBuilder As New SqlCommandBuilder(daInstDeleteTbl)
daInstDeleteTbl.Update(dsDeleteInst)
Dim daInstTbl As _
New SqlDataAdapter("SELECT * FROM Table WHERE Column = 'b'", objConn)
Dim objCommandReBuilder As New SqlCommandBuilder(daInstTbl)
daInstTbl.Update(dsNewInst)
End Sub
I think I am doing a lot of extra work just to do this wrong. Any ideas? Thanks.
When you invoke SqlDataAdapter.Update() the adapter updates the values in the database by executing the respective INSERT, UPDATE, or DELETE (from MSDN). The SELECT command is not executed. So you need to do it like this:
Insert/Update/Delete:
daInstTbl.Update(dsNewInst)
Select:
daInstTbl.Fill(dsNewInst)
Commit:
dsNewInst.AcceptChanges()
Example
Private connection As SqlConnection
Private adapter As SqlDataAdapter
Private data As DataSet
Private builder As SqlCommandBuilder
Private grid As DataGridView
Private Sub InitData()
Me.SqlSelect(firstLoad:=True, fillLoadOption:=LoadOption.OverwriteChanges, acceptChanges:=True)
Me.grid.DataSource = Me.data
Me.grid.DataMember = "Table"
End Sub
Public Sub SaveData()
Me.SqlInsertUpdateAndDelete()
Me.SqlSelect(fillLoadOption:=LoadOption.OverwriteChanges, acceptChanges:=True)
End Sub
Public Sub RefreshData(preserveChanges As Boolean)
Me.SqlSelect(fillLoadOption:=If(preserveChanges, LoadOption.PreserveChanges, LoadOption.OverwriteChanges))
End Sub
Private Sub SqlSelect(Optional firstLoad As Boolean = False, Optional ByVal fillLoadOption As LoadOption = LoadOption.PreserveChanges, Optional acceptChanges As Boolean = False)
If (firstLoad) Then
Me.data = New DataSet()
Me.connection = New SqlConnection("con_str")
Me.adapter = New SqlDataAdapter("SELECT * FROM Table WHERE Column = 'b'", connection)
Me.builder = New SqlCommandBuilder(Me.adapter)
End If
Me.connection.Open()
If (firstLoad) Then
Me.adapter.FillSchema(Me.data, SchemaType.Source, "Table")
End If
Me.adapter.FillLoadOption = fillLoadOption
Me.adapter.Fill(Me.data, "Table")
If (acceptChanges) Then
Me.data.Tables("Table").AcceptChanges()
End If
Me.connection.Close()
End Sub
Private Sub SqlInsertUpdateAndDelete()
If (Me.connection.State <> ConnectionState.Open) Then
Me.connection.Open()
End If
Me.adapter.Update(Me.data, "Table")
Me.connection.Close()
End Sub
PS: (Untested code)
My solution was to change the way I was declaring variables. Before I had:
Dim daInstTbl As _
New SqlDataAdapter("SELECT * FROM Table WHERE Column = 'b'", objConn)
The affect was that recalling the subroutine ignored this line because the variable daInstTbl was already declared previously. The solution was:
' Delete old instance of a Data____ classes
da = Nothing
ds = Nothing
dt = Nothing
If GetAll = False Then
da = New SqlDataAdapter(sSelCmd, objConn)
Else
da = New SqlDataAdapter(sSelAllCmd, objConn)
End If
' Create an instance of a DataSet, and retrieve data from the Authors table.
ds = New DataSet
da.FillSchema(ds, SchemaType.Source)
da.Fill(ds)
This cleared the information and allowed me to assign a new value. My subroutines serve double duty by assigning two query strings and then using an optional boolean to determine which version to use.
Dim sSelCmd As String = "SELECT * FROM Table WHERE Coloumn= 'b'"
Dim sSelAllCmd As String = "SELECT * FROM Table"
Private Sub GetData(Optional ByVal GetAll As Boolean = False)
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
And that leads into the code above! Thanks for the help. Some of your concepts got my thoughts turning in the right direction and motivated me to clean up my code into a much more readable form.

VB.Net Silverlight 5 SQL Entities Searching

Im making a silverlight 5 application and im using RIA WCS services to connect to sql, i can add data,delete data, edit data, and get all data, but the problem is that i need to retrieve a specific record not the whole entity, when i try the following code just nothing happens:
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
' InitializeComponent()
objctx = New BanksDomainContext
Dim itemType = Branch_NameComboBox.SelectedItem.GetType
Dim pi = itemType.GetProperty(Branch_NameComboBox.DisplayMemberPath)
Dim cbi = pi.GetValue(Branch_NameComboBox.SelectedItem, Nothing).ToString()
Dim BranchName As String = cbi
' Dim query As EntityQuery(Of Branches) = objctx.GetBranchesDetailsQuery(BranchName)
' Dim loadOp As LoadOperation(Of Branches) = Me.objctx.Load(query)
' DataGrid1.ItemsSource = loadOp.Entities
' objctx.Load(query, LoadData, Nothing)
Dim loadOp = Me.objctx.Load(Me.objctx.GetBranchesDetailsQuery(BranchName))
LoadData(loadOp)
End Sub
Private Sub LoadData(lo As LoadOperation)
For Each br As Branches In lo.Entities
AddressTextBlock.Text = br.Address
CoordinatesTextBlock.Text = br.Coordinates
ManagerTextBlock.Text = br.Manager
PhoneTextBlock.Text = br.Phone
FaxTextBlock.Text = br.Fax
Next
End Sub
can someone guide me on how to do it?
The following is the solution to load text boxes from SQL records by selecting the search term from a list box:
Private Sub Branch_NameComboBox_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles Branch_NameComboBox.SelectionChanged
m_PushpinLayer.Children.Clear()
objctx = New BanksDomain
Dim itemType = Branch_NameComboBox.SelectedItem.[GetType]()
Dim pi = itemType.GetProperty(Branch_NameComboBox.DisplayMemberPath)
Dim cbi = pi.GetValue(Branch_NameComboBox.SelectedItem, Nothing).ToString()
Dim BranchName As String = cbi
Dim itemType2 = NameComboBox.SelectedItem.[GetType]()
Dim pi2 = itemType2.GetProperty(NameComboBox.DisplayMemberPath)
Dim cbi2 = pi2.GetValue(NameComboBox.SelectedItem, Nothing).ToString()
Dim BankName As String = cbi2
Dim bb As EntityQuery(Of Branches) = From b In objctx.GetBranchesDetailsQuery(BranchName) Where b.Bank = BankName Select b
Dim res As LoadOperation(Of Branches) = objctx.Load(bb, New Action(Of LoadOperation(Of Branches))(AddressOf GetBeansCompleted), True)
End Sub
Private Sub GetBeansCompleted(args As LoadOperation(Of Branches))
For Each bc As Branches In args.Entities
'
Dim Latitude As Double = bc.Lat
Dim Longitude As Double = bc.Lon
Dim CoO As Location = New Location
CoO.Latitude = Decimal.Parse(Latitude)
CoO.Longitude = Decimal.Parse(Longitude)
Dim BName As String = bc.Branch_Name.ToString
Dim MKColor As Color = GetThisColor(bc.MapKeyColor.ToString)
AddPushPin(BName, CoO, MKColor)
AddressTextBlock.Text = (bc.Address.ToString)
LatTextBlock.Text = (Decimal.Parse(Latitude))
LonTextBlock.Text = (Convert.ToDecimal(Longitude))
ManagerTextBlock.Text = (bc.Manager.ToString)
PhoneTextBlock.Text = (bc.Phone.ToString)
FaxTextBlock.Text = (bc.Fax.ToString)
Next
End Sub