Combobox not being filled after introduction of login form - vb.net

I have the following code in my UC_Menu_Scout class:
Private Sub cmbScoutName_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbScoutName.SelectedIndexChanged
If loaded = True Then
cmbReportDate.DataSource = Nothing
cmbReportDate.DataSource = frmPlayerInfo.filterReports()
cmbReportDate.DisplayMember = "ReportDate"
cmbReportDate.ValueMember = "ReportID"
End If
End Sub
Private Sub cmbReportDate_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbReportDate.SelectedIndexChanged
If loaded = True Then
If cmbReportDate.Items.Count > 0 Then
'frmPlayerInfo.myDataTable = Nothing
frmPlayerInfo.myDataTable = frmPlayerInfo.retrieveDT()
dgPlayers.DataSource = frmPlayerInfo.myDataTable
frmPlayerInfo.setReport()
End If
End If
End Sub
And the following code in my frmPlayerInfo class (just the relevant code):
Public myDataTable As DataTable = Nothing
Private Sub frmPlayerInfo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
UC_Menu_Scout1.cmbScoutName.DataSource = retrieveScouts()
UC_Menu_Scout1.cmbScoutName.DisplayMember = "ScoutName"
UC_Menu_Scout1.cmbScoutName.ValueMember = "ScoutID"
UC_Menu_Scout1.cmbReportDate.DataSource = filterReports()
UC_Menu_Scout1.cmbReportDate.DisplayMember = "ReportDate"
UC_Menu_Scout1.cmbReportDate.ValueMember = "ReportID"
myDataTable = retrieveDT()
UC_Menu_Scout1.dgPlayers.DataSource = myDataTable
setReport()
loaded = True
End Sub
Public Function retrieveDT() As DataTable
Dim Str As String = _
<String> SELECT
Player.PlayerID,
PlayerFirstName,
PlayerLastName,
DOB,
Age,
PlaceOfBirth,
PlayerImage
FROM
Player
INNER JOIN
Report ON Report.PlayerID = Player.PlayerID
/*WHERE
ReportID = #ReportID*/
ORDER BY
PlayerFirstName
</String>
Dim dt As New DataTable
Using conn As New SqlClient.SqlConnection(DBConnection)
conn.Open()
Using cmdQuery As New SqlClient.SqlCommand(Str, conn)
cmdQuery.Parameters.Add("#ReportID", SqlDbType.Int).Value = UC_Menu_Scout1.cmbReportDate.SelectedItem.ReportID
cmdQuery.CommandTimeout = 600
Try
Using daResults As New SqlClient.SqlDataAdapter(cmdQuery)
daResults.Fill(dt)
End Using
Catch ex As Exception
MsgBox("An Exception has happened: " & ex.Message & vbNewLine)
End Try
End Using 'Automatically closes connection
End Using
Return dt
End Function
Everything worked fine before I created a login form. Since then (upon a successful login) I've been receiving the "Object variable or with block variable not set" error on my comboboxes- saying they were now empty at the time of the form load event. Since setting the "loaded" boolean, this got rid of the error for frmPlayerInfo.filterReports(), however I still receive the same message for frmPlayerInfo.retrieveDT- on this line cmdQuery.Parameters.Add("#ReportID", SqlDbType.Int).Value = UC_Menu_Scout1.cmbReportDate.SelectedItem.ReportID. Again, saying the combobox (cmbReportDate) is empty.
The intial load event works, but the crash occurs on the cmbReportDate_SelectedIndexChanged event, on this line: frmPlayerInfo.myDataTable = frmPlayerInfo.retrieveDT() in the retrieveDT function.
If I remove the login form I have no such problems- any answers specific to my program would be appreciated.

Here's an example of how to get a reference to the main Form from within your UserControl:
Dim frm As Form = Me.FindForm
If TypeOf frm Is frmPlayerInfo Then
Dim player As frmPlayerInfo = DirectCast(frm, frmPlayerInfo)
' ... now do something with "player" ...
End If
No, this is not a good design because now your UserControl can only ever be used with the frmPlayerInfo Form. If you're okay with that, then here's an example using your specific code:
Private Sub cmbReportDate_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbReportDate.SelectedIndexChanged
If loaded = True Then
If cmbReportDate.Items.Count > 0 Then
Dim frm As Form = Me.FindForm
If TypeOf frm Is frmPlayerInfo Then
Dim player As frmPlayerInfo = DirectCast(frm, frmPlayerInfo)
' ... now do something with "player" ...
player.myDataTable = player.retrieveDT()
dgPlayers.DataSource = player.myDataTable
player.setReport()
End If
End If
End If
End Sub

Related

Datagridview form always open with row in selected state

I have two forms: frmMain and frmProduct
In the main form frmMain, I have a Datagridview1 and the buttons: tsbInsert_click, tsbAlter_click and tsbConsult_click.
When I open the main form frmMain, there is still no row in the Datagridview1 and when I click on any of the tsbAlter_click or tsbConsult_click buttons, the code displays the message "Select a product", which is correct , because there is still no product created in the register.
When I click on the tsbInsert_click button, the code opens the frmProduct to insert a record in the register and then returns to the main form frmMain, which, in the line of the Datagridview1, shows the record that was included.
The problem is that when I include a record in the register, the Datagridview1 ALWAYS returns with the state of the selected row, and the condition If DGProducts.CurrentRow Is Nothing is never true again ... so when I click on tsbAlter_click or tsbConsult_click, the "Select a product" message no longer appears and it should have since I didn't select any rows in Datagridview1.
frmMain Code:
Public Class frmMain
Private Sub tsbInsert_Click(sender As Object, e As EventArgs) Handles tsbInsert.Click
Using frm As New frmProduct("Insert", "")
frm.ShowDialog()
If frm.txtPrdCod.Text <> "" Then
DGProducts.Rows.Add(Campo(0), Campo(1), Campo(2))
End If
End Using
End Sub
Private Sub tsbAlter_Click(sender As Object, e As EventArgs) Handles tsbAlter.Click
If DGProducts.CurrentRow Is Nothing Then
MessageBox.Show("Select a product")
Exit Sub
End If
Dim codProd As String = DGProducts.CurrentRows.Cells("prdCod").Value
Using frm As New frmProduct("Alter", codProd)
frm.ShowDialog()
With DGProducts.Rows(DGProds.CurrentCell.RowIndex)
.Cells("prdCod").Value = Field(0)
.Cells("prdName").Value = Field(1)
.Cells("prdManufac").Value = Field(2)
End With
End Using
End Sub
Private Sub DGProducts_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles DGProducts.CellEnter
With DGProducts.Rows(DGProducts.CurrentCell.RowIndex)
Campo(0) = .Cells("prdCod").Value
Campo(1) = .Cells("prdName").Value
Campo(2) = .Cells("prdManufac").Value
End With
End Sub
End Class
frmProduct code:
Public Class frmProduct
Private Sub frmProduct_Load(sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If _operation = "Alter" Then
txtPrdCod.Text = Campo(0)
txtPrdName.Text = Campo(1)
txtManufct.Text = Campo(2)
Else
txtPrdCod.Text = ""
txtPrdName.Text = ""
txtManufct.Text = ""
Enf If
End Sub
Dim _operation As String
Dim _codProd As String
Public Sub New(operation As String, codProd As String)
InitializeComponent()
Select Case operation
Case "Insert"
_operation = operation
Case "Alter"
_operation = operation
_codProd = codProd
Case Else
MessageBox.Show("Invalid option!")
Close()
End Select
End Sub
Private Sub tsbRecord_Click(sender As Object, e As EventArgs) Handles tsbRecord.Click
Field(0) = txtPrdCod.Text
Field(1) = txtPrdName.Text
Field(2) = txtManufct.Text
Me.Close()
End Sub
End Class
How do I make it so that when I add a product to the register, Datagridview1 DOES NOT return with the line in the SELECTED state and the message "Select a product" appears when I don't select a line from Datagridview1?
The command DGProducts.Rows.Add(Field(0), Field(1), Field(2)), automatically changes the value DGProducts.SelectedRows.Count to 1, so I set DGProducts.CurrentCell = Nothing after command DGProducts.Rows.Add in code:
Private Sub tsbInsert_Click(sender As Object, e As EventArgs) Handles tsbInsert.Click
Using frm As New frmProduct("Insert", "")
frm.ShowDialog()
If frm.txtPrdCod.Text <> "" Then
DGProducts.Rows.Add(Campo(0), Campo(1), Campo(2))
DGProducts.CurrentCell = Nothing
End If
End Using
End Sub

Login the user when he confirms the email address

Using Microsoft.AspNet.Identity i have almost all I need to manage the users problems, but I ( a vb.net beginner) can't update this code to automatically sign in the user when he confirm the email address.
I think I need a method to get ApplicationUser just based on UsedId
This is the code I try to change:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim code As String = IdentityHelper.GetCodeFromRequest(Request)
Dim userId As String = IdentityHelper.GetUserIdFromRequest(Request)
If code IsNot Nothing AndAlso userId IsNot Nothing Then
Dim manager = Context.GetOwinContext().GetUserManager(Of ApplicationUserManager)()
Dim result = manager.ConfirmEmail(userId, code)
If result.Succeeded Then
'>>>>>>>>login the user
successPanel.Visible = True
Return
End If
End If
successPanel.Visible = False
errorPanel.Visible = True
End Sub
In case someone else have this issue, this is the code i used
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim code As String = IdentityHelper.GetCodeFromRequest(Request)
Dim userId As String = IdentityHelper.GetUserIdFromRequest(Request)
If code IsNot Nothing AndAlso userId IsNot Nothing Then
Dim manager = Context.GetOwinContext().GetUserManager(Of ApplicationUserManager)()
Dim result = manager.ConfirmEmail(userId, code)
If result.Succeeded Then
Try
Dim task = New UserStore(Of Sue.ApplicationUser)(Context.GetOwinContext().[Get](Of ApplicationDbContext)()).FindByIdAsync(userId)
Dim user = task.Result()
Dim signInManager = Context.GetOwinContext().Get(Of ApplicationSignInManager)()
signInManager.SignIn(user, isPersistent:=False, rememberBrowser:=False)
Context.Response.Redirect("/Account/UserData", False)
Catch ex As Exception
successPanel.Visible = False
errorPanel.Visible = True
Return
End Try
End If
End If
successPanel.Visible = False
errorPanel.Visible = True
End Sub

HOW TO FILL COMBO BOX IN VB.NET

I have a code to fill my combo box but every time i close the form the list is being doubled, if i have a list from my database of English, Mathematics, Science after i close the form and open it again the list showing is now English, Mathematics, Science, English, Mathematics, Science
HERE IS THE CODE,
Call OpenDB()
cmd.CommandText = "select * from Subject"
cmd.Connection = conn
dr = cmd.ExecuteReader
While dr.Read()
cmbSubject.Items.Add(dr("Subject Name"))
End While
dr.Close()
Call CloseDB()
The problem is not in the method you are using to bind the combobox. in each time it binds that's why you are getting duplicate records in the database. to avoid this please clear the combobox before each bind, like the following:
Call OpenDB()
cmbSubject.Items.Clear ' extra statement added to clear the item collection
cmd.CommandText = "select * from Subject"
cmd.Connection = conn
dr = cmd.ExecuteReader
While dr.Read()
cmbSubject.Items.Add(dr("Subject_Name"))
End While
dr.Close()
Call CloseDB()
If you need an alternate method for binding the combobox i will suggest you binding with Dataset
following is the example code for this :
Dim SQL As String= "select Subject_Name,Subject_code from Subject"
Dim adapter As New OdbcDataAdapter(SQL, conn) '<-- This function will Retrieve Data and Return as Dataset together with table name
Dim myData As New DataSet
myData.Fill(lobjDataSet, tblName)
cmbSubject.DataSource = ds_myData
cmbSubject.DataMember = "Subject"
cmbSubject.DataTextField = "Subject_Name"
cmbSubject.DataValueField = "Subject_code"
cmbSubject.DataBind()
myData .Dispose()
Public Class frmRegistration
Dim obj As New Entity.Registration
Dim bus As New Business.Registration
Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
BindingSource1.EndEdit()
bus.Save(obj)
RefreshGrid()
MsgBox("Saved.")
End Sub
Sub RefreshGrid()
Dim dt1 As DataTable = bus.Select()
BindingSource2.DataSource = dt1
DataGridView1.AllowUserToAddRows = False
DataGridView1.DataSource = BindingSource2
End Sub
Private Sub Registration_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
RefreshGrid()
NewItem()
End Sub
Private Sub BtnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnNew.Click
NewItem()
End Sub
Sub ResetDis()
BindingSource1.DataSource = obj
End Sub
Sub NewItem()
obj = New Entity.Registration
ResetDis()
End Sub
Private Sub BindingSource2_CurrentChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BindingSource2.CurrentChanged
obj = New Entity.Registration(CType(Me.BindingSource2.Current, DataRowView).Row)
ResetDis()
End Sub
End Class

Auto-fill textbox on a dialog form, from a Datagridview on the original form, vb.net 2013

I am currently working in windows form applications using vb.net 2013. I have two forms, we can call them form1 and form 2 for now. Form1 has a datagridview with a checkbox column that the end user will click to open form2 as a dialog form. Once form2 opens I want it to automatically load and fill two text boxes that have information from corresponding columns from the original DGV. In short, the DGV on form1 has 3 columns; JobNumber, LineNumber, and the checkbox. The end user will click the checkbox to bring up form2 and I want the Jobnumber and Linenumber to automaticaly fill into two textboxes on form2. Here is my code from form1.
'assembly dialog result form
dr = f.ShowDialog
If dr = Windows.Forms.DialogResult.OK Then
'dim y as job string
Dim Y As String = DataGridOrdered.Rows(e.RowIndex).Cells(3).Value
'open connection
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("UPDATE Production.dbo.tblFCOrdered SET Complete = 1, RackIn = 1 WHERE JobNumber = '" & Y & "'", conn1)
comm1.ExecuteNonQuery()
conn1.Close()
End Using
End Using
Call DGVOrderedRefresh()
ElseIf dr = Windows.Forms.DialogResult.Yes Then
'dim M as job string
Dim M As String = DataGridOrdered.Rows(e.RowIndex).Cells(3).Value
'open connection
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("UPDATE Production.dbo.tblFCOrdered SET Complete = 1, RackIn = 1 WHERE JobNumber = '" & M & "'", conn1)
comm1.ExecuteNonQuery()
conn1.Close()
End Using
End Using
Call DGVOrderedRefresh()
ElseIf dr = Windows.Forms.DialogResult.Cancel Then
'refresh datagridview ordered
Call DGVOrderedRefresh()
End If
ElseIf e.ColumnIndex = 0 Then
'fail safe to make sure the header is not clicked
If e.RowIndex = -1 Then
Exit Sub
End If
The code for my dialog is as follows
Imports System.Data
Imports System.Data.SqlClient
Public Class BuildName
' Dim connstring As String = "DATA SOURCE = BNSigma\CORE; integrated security = true"
Dim connstring As String = "DATA SOURCE = BNSigma\TEST; integrated security = true"
Private Sub Label3_Click(sender As Object, e As EventArgs) Handles Label3.Click
End Sub
Private Sub BuildName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ds As New DataTable
Try
'load name combo box
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("SELECT Name FROM Production.dbo.FCNames", conn1)
Dim adapater As New SqlDataAdapter
adapater.SelectCommand = comm1
adapater.Fill(ds)
adapater.Dispose()
conn1.Close()
CBName.DataSource = ds
CBName.DisplayMember = "Name"
CBName.ValueMember = "Name"
End Using
End Using
Catch ex As Exception
MsgBox("Error loading name List, please contact a mfg. Engr.!")
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Update built by name
Dim v As Object = TBFloor.Text
Dim G As Object = TBLine.Text
Dim O As Object = TBJobNumber.Text
Try
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("UPDATE Production.dbo.tblFCOrdered SET BuiltBy = #Name Where JobNumber = '" & O & "'", conn1)
comm1.Parameters.AddWithValue("#Name", CBName.Text)
comm1.ExecuteNonQuery()
conn1.Close()
End Using
End Using
Catch ex As Exception
MsgBox("Error updating Ordered table, please contact a MFG. ENGR.!")
MsgBox(ex.ToString)
End Try
End Sub
End Class
UPDATED CODE FOR VALTER
Form1 code
Public row_Index As Integer = 0
Private Sub DataGridOrdered_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles DataGridOrdered.CurrentCellDirtyStateChanged
If DataGridOrdered.IsCurrentCellDirty Then
DataGridOrdered.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
Private Sub DataGridOrdered_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridOrdered.CellValueChanged
If DataGridOrdered.Columns(e.ColumnIndex).Name = 9 Then
Dim checkCell As DataGridViewCheckBoxCell = CType(DataGridOrdered.Rows(e.RowIndex).Cells(9), DataGridViewCheckBoxCell)
If CType(checkCell.Value, [Boolean]) = True Then
row_Index = e.RowIndex
BuildName.ShowDialog(Me)
End If
End If
End Sub
Form 2 code
Private Sub BuildName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value1 As Object = FormOrdered.DataGridOrdered.Rows(FormOrdered.row_Index).Cells(3).Value
Dim value2 As Object = FormOrdered.DataGridOrdered.Rows(FormOrdered.row_Index).Cells(4).Value
TBJobNumber.Text = CType(value1, String)
TBFloor.Text = CType(value2, String)
In your form1 add:
Public Row_Index As Integer = 0 //use a simple variable
Sub datagridOrdered_CurrentCellDirtyStateChanged( _
ByVal sender As Object, ByVal e As EventArgs) _
Handles datagridOrdered.CurrentCellDirtyStateChanged
If datagridOrdered.IsCurrentCellDirty Then
datagridOrdered.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
Private Sub datagridOrdered_CellValueChanged(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles datagridOrdered.CellValueChanged
If datagridOrdered.Columns(e.ColumnIndex).Name = "Assemble" Then //<- here
Dim checkCell As DataGridViewCheckBoxCell = _
CType(datagridOrdered.Rows(e.RowIndex).Cells(2), _ //<- here
DataGridViewCheckBoxCell)
If CType(checkCell.Value, [Boolean]) = True Then
//RowIndex = e.RowIndex you dont need this
Row_Index = e.RowIndex
BuildName.ShowDialog(Me)
End If
End If
End Sub
//Nor this
//Private _count As Integer
//Public Property RowIndex() As Integer
//Get
//Return _count
//End Get
//Set(value As Integer)
//_count = value
//End Set
//End Property
And in dialog load event use Form1.Row_Index instead:
Private Sub BuildName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value1 As Object = FormOrdered.datagridOrdered.Rows(Form1.Row_Index).Cells(0).Value //<- here
Dim value2 As Object = FormOrdered.datagridOrdered.Rows(Form1.Row_Index).Cells(1).Value //<- here
TBJobNumber.Text = CType(value1, String)
TBFloor.Text = CType(value2, String)
...
...
End Sub
or add a module and add the Row_Index there. You can use it then as is
Private Sub BuildName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value1 As Object = FormOrdered.DataGridView1.Rows(Row_Index).Cells(0).Value
Dim value2 As Object = FormOrdered.DataGridView1.Rows(Row_Index).Cells(1).Value
TBJobNumber.Text = CType(value1, String)
TBFloor.Text = CType(value2, String)
...
...
End Sub

Public variable used for form opening not feeding through to from

Having some issues getting a form to populate based on a variable determined in current form.
I have a search result form that has a datagrid with all results, with an open form button for each row. When the user clicks this, the rowindex is used to pull out the ID of that record, which then feeds to the newly opened form and populates based on a SQL stored procedure run using the ID as a paramter.
However, at the moment the variable is not feeding through to the form, and am lost as to why that is. Stored procedure runs fine if i set the id within the code. Here is my form open code, with sci
Public Class SearchForm
Dim Open As New FormOpen
Dim data As New SQLConn
Public scid As Integer
Private Sub Search_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sql As New SQLConn
Call sql.SearchData()
dgvSearch.DataSource = sql.dt.Tables(0)
End Sub
Private Sub dgvSearch_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSearch.CellContentClick
Dim rowindex As Integer
Dim oform As New SprinklerCardOpen
rowindex = e.RowIndex.ToString
scid = dgvSearch.Rows(rowindex).Cells(1).Value
TextBox1.Text = scid
If e.ColumnIndex = 0 Then
oform.Show()
End If
End Sub
End Class
The form opening then has the follwing:
Private Sub SprinklerCard_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Populate fields from SQL
Try
Call Populate.SprinklerCardPopulate(ID)
cboInsured.Text = Populate.dt.Tables(0).Rows(0).Item(1)
txtAddress.Text = Populate.dt.Tables(0).Rows(0).Item(2)
txtContactName.Text = Populate.dt.Tables(0).Rows(0).Item(3)
txtContactPhone.Text = Populate.dt.Tables(0).Rows(0).Item(4)
txtContactEmail.Text = Populate.dt.Tables(0).Rows(0).Item(5)
numPumps.Value = Populate.dt.Tables(0).Rows(0).Item(6)
numValves.Value = Populate.dt.Tables(0).Rows(0).Item(7)
cboLeadFollow.Text = Populate.dt.Tables(0).Rows(0).Item(8)
cboImpairment.Text = Populate.dt.Tables(0).Rows(0).Item(9)
txtComments.Text = Populate.dt.Tables(0).Rows(0).Item(10)
Catch ex As Exception
MsgBox(ex.ToString & "SCID = " & ID)
End Try
End Sub
Set the ID variable in the form before you open it.
If e.ColumnIndex = 0 Then
oform.ID = scid
oform.Show()
End If