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

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

Related

Need help editing Customer Info in VB.net

I am trying to edit customers using my C# project to learn how to implement this code in VB.net. The project was successful in adding customers, but when it got to editing customers, things got a bit more complicated because I needed to get the id of the row selected and pass it to a string. I have the MainForm.vb which could open CustomerForm.vb when I click on 'Edit'. When CustomerForm.vb opens, it failed to show the customer's info. I am not sure if FillDataTable() function is necassary, I would like to know if there is an improvement to this.
CustomerForm.vb
Imports System.Data.SqlClient
Public Class CustomerForm
Private objConnection As SqlConnection
Public objDataTable As DataTable = New DataTable()
Public objSqlCommand As SqlCommand = New SqlCommand()
Public editMode As Boolean = False
Public id As String = ""
Public FName As String = ""
Public LName As String = ""
Public PhNumber As String = ""
Public ReadOnly Property Connection As SqlConnection
Get
Return Me.objConnection
End Get
End Property
Dim CS As String = ("server=CASHAMERICA;Trusted_Connection=yes;database=ProductsDatabase2; connection timeout=30")
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If editMode = False Then
If txtFirstName.Text = "" Then
MessageBox.Show("First Name Is required")
ElseIf txtLastName.Text = "" Then
MessageBox.Show("Last Name Is required")
Else
Dim con As New SqlConnection(CS)
con.Open()
Dim cmd As New SqlCommand("INSERT INTO Customers(FIrstName,LastName,PhoneNumber) VALUES(#FName, #LName, #PhNumber)", con)
cmd.Parameters.AddWithValue("#FName", txtFirstName.Text)
cmd.Parameters.AddWithValue("#LName", txtLastName.Text)
cmd.Parameters.AddWithValue("#PhNumber", txtPhoneNumber.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Customer has been added!")
con.Close()
End If
ElseIf editMode = True Then
If txtFirstName.Text = "" Then
MessageBox.Show("First Name Is required")
ElseIf txtLastName.Text = "" Then
MessageBox.Show("Last Name Is required")
Else
Dim con As New SqlConnection(CS)
con.Open()
Dim cmd As New SqlCommand("UPDATE Customers SET FIrstName = #FName, LastName = #LName, PhoneNumber = #PhNumber WHERE Id = #Id", con)
cmd.Parameters.AddWithValue("#Id", id)
cmd.Parameters.AddWithValue("#FName", txtFirstName.Text)
cmd.Parameters.AddWithValue("#LName", txtLastName.Text)
cmd.Parameters.AddWithValue("#PhNumber", txtPhoneNumber.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Customer has been edited.")
con.Close()
End If
End If
Catch ex As Exception
MessageBox.Show(Me, ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
Me.Close()
End Sub
Private Sub CustomerForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If editMode = False Then
GetId()
Else
textId.Text = id
txtFirstName.Text = FName
txtLastName.Text = LName
txtPhoneNumber.Text = PhNumber
End If
End Sub
Private Sub GetId()
Dim con As New SqlConnection(CS)
con.Open()
Dim cmd As New SqlCommand("SELECT MAX(id)+1 FROM Customers")
textId.Text = FillDataTable().Rows(0)(0).ToString()
If textId.Text = "" Then
textId.Text = "1"
End If
End Sub
Public Property CommandText As String
Get
Return CommandText
End Get
Set(ByVal value As String)
CommandText = value
End Set
End Property
Public Sub OpenDBConnection()
objConnection = New SqlConnection(CS)
objConnection.Open()
End Sub
Public Sub CreateCommandObject()
objSqlCommand = objConnection.CreateCommand()
objSqlCommand.CommandText = CommandText
objSqlCommand.CommandType = CommandType.Text
End Sub
Public Function FillDataTable() As DataTable
objDataTable = New DataTable()
objSqlCommand.CommandText = CommandText
objSqlCommand.Connection = objConnection
objSqlCommand.CommandType = CommandType.Text
objDataTable.Load(objSqlCommand.ExecuteReader())
objConnection.Close()
Return objDataTable
End Function
Public Sub CloseConnection()
If objConnection IsNot Nothing Then objConnection.Close()
End Sub
End Class
MainForm.vb
Imports System.Windows.Forms.LinkLabel
Public Class MainForm
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Me.Close()
End Sub
Private Sub AddToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddToolStripMenuItem.Click
CustomerForm.ShowDialog()
End Sub
Private Sub AddToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles AddToolStripMenuItem1.Click
ProductForm.ShowDialog()
End Sub
Private Sub ViewProductsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ViewProductsToolStripMenuItem.Click
ManageProductsForm.ShowDialog()
End Sub
Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
AboutForm.Show()
End Sub
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'ProductsDatabase2DataSet1.Customers' table. You can move, or remove it, as needed.
Me.CustomersTableAdapter.Fill(Me.ProductsDatabase2DataSet1.Customers)
End Sub
Private Sub gridCustomers_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles gridCustomers.MouseUp
Try
Dim f As CustomerForm = New CustomerForm()
f.editMode = True
Dim rowIndex As Integer = gridCustomers.CurrentCell.RowIndex
f.id = gridCustomers.Rows(rowIndex).Cells("colId").Value.ToString()
f.FName = gridCustomers.Rows(rowIndex).Cells("colFirstName").Value.ToString()
f.LName = gridCustomers.Rows(rowIndex).Cells("colLastName").Value.ToString()
f.PhNumber = gridCustomers.Rows(rowIndex).Cells("colPhoneNumber").Value.ToString()
f.Show()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub gridCustomers_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles gridCustomers.CellContentClick
Dim f As CustomerForm = New CustomerForm()
f.ShowDialog(Me)
f.editMode = True
End Sub
End Class
Error Message:
Customer Info not displayed:
As mentioned, it seems like you have several things potentially going on.
The first thing I would change is your public sql objects. You don't need them to be public. It also increases the chances for issues if you're using the same objects in multiple places.
SqlCommand, SqlConnection, and SqlDataAdapters can be immediately disposed of (in most cases) as soon as they are used.
One easy method to handling all of that is to throw everything inside of a USING block.
Dim sqlResult As New Datatable()
Using cn As New SqlConnection("Connection String here"),
cmd As New SqlCommand(sql, cn),
adapt As New SqlDataAdapter(cmd)
cn.Open()
'Handle stored procedure vs select options
If sql.Contains("SELECT") Then
cmd.CommandType = CommandType.Text
Else
cmd.CommandType = CommandType.StoredProcedure
End If
'If parameters passed, else comment out
cmd.Parameters.AddWithValue("#parameterName", parameterValue)
sqlResult = New DataTable(cmd.CommandText)
adapt.Fill(sqlResult)
End Using
Now all your objects are disposed of as soon as your datatable is filled.
*This example uses a datatable, but it is the same idea for anything interacting with sql objects.
If implemented, you may find out that some objects weren't being disposed of or initialized properly.
Another method for testing where things are going wrong is to query the states of the SQL objects before or around the error to see if something isn't set correctly or is uninitialized.

Trying to get SUM of ListBox selected items from local DataTable into a Label

I have been searching for days, for any possible reference or suggestions and everything I've come across hasn't worked.
The goal:
User will select options in ComboBox1 that will then determine the available options in ComboBox2, then will populate a list of operations in ListBox1.
When the user selects available operations in ListBox1, I need the output to be the sum of values (total time in minutes in this case) into a label for display.
The data used in stored in a local db. So far everything works with my comboboxes and the listbox.
Im attempting to get the Text value, of all selected items, in ListBox1 to output the numeric value in my table (column 4 "OperationsTime"), into a label that will display the sum of all the selections (Total Time In Minutes).
Some Things I have Tried From Other Posts:
Label9.Text = ListBox1.ValueMember
Label9.Text = ListBox1.ValueMember.ToString
Label9.Text = CType(ListBox1.SelectedItem, DataRowView).Row.Item("OperationsTime").ToString
Attempted using Double:
Dim Total As Double = 0
For Each Time As Integer In ListBox1.SelectedItems
Total += CDbl(Time.ToString.Substring(Time.ToString.LastIndexOf(",") + 1))
Next
Label9.Text = Total.ToString
Screen Shot of the Table:
Operations Data Table
Below is my code:
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Public Class MainHome
Private Function GetData(ByVal sql As String) As DataTable
Dim constr As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\hartj\Documents\visual studio 2015\Projects\TIMEMATRIX2.0\TIMEMATRIX2.0\TMX.mdf;Integrated Security=True"
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
Dim row As DataRow = dt.NewRow()
row(0) = 1
row(1) = "Please Select"
dt.Rows.InsertAt(row, 0)
Return dt
End Using
End Using
End Function
Private Sub MainHome_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
ComboBox1.DataSource = Me.GetData("SELECT SizeId, SizeName FROM Size")
ComboBox1.DisplayMember = "SizeName"
ComboBox1.ValueMember = "SizeId"
ComboBox2.Enabled = False
ComboBox3.Enabled = False
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
ComboBox2.DataSource = Nothing
ComboBox3.DataSource = Nothing
ComboBox2.Enabled = False
ComboBox3.Enabled = False
If ComboBox1.SelectedValue.ToString() <> "0" Then
Dim sql As String = String.Format("SELECT DetailLevelId, DetailLevelName FROM DetailLevel WHERE SizeId = {0}", ComboBox1.SelectedValue)
ComboBox2.DataSource = Me.GetData(sql)
ComboBox2.DisplayMember = "DetailLevelName"
ComboBox2.ValueMember = "DetailLevelId"
ComboBox2.Enabled = True
End If
End Sub
Private Sub ComboBox2_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox2.SelectionChangeCommitted
ListBox1.DataSource = Nothing
ListBox1.Enabled = False
If ComboBox2.SelectedValue.ToString() <> "0" Then
Dim sql As String = String.Format("SELECT OperationsId, OperationsName, OperationsTime FROM Operations WHERE DetailLevelId = {0}", ComboBox2.SelectedValue)
ListBox1.DataSource = Me.GetData(sql)
ListBox1.ValueMember = "OperationsName"
ListBox1.ValueMember = "OperationsTime"
ListBox1.Enabled = True
Label9.Text = CType(ListBox1.SelectedValue, Integer).ToString
'Label.Text = CType(cbbank.SelectedItem, DataRowView).Row.Item("Account").ToString
End IF
End Sub
Dim totalOperationsTime As Double
For Each view As DataRowView In ListBox1.SelectedItems
totalOperationsTime += CDbl(view("OperationsTime"))
Next
There's no need to get the DataRow from the DataRowView because you can access the field values directly from the DataRowView. It can and does do many of the same things that the DataRow does.
That's the most conventional way but there are other options too. You could throw some LINQ at it:
Dim totalOperationsTime = ListBox1.SelectedItems.Cast(Of DataRowView)().
Sum(Function(view) CDbl(view("OperationsTime")))
It is somewhat annoying that the ValueMember property only helps you get a value for the SelectedItem. Here's a class I wrote some time ago that adds a GetItemValue method that makes use of the ValueMember much as the GetItemText method does for the DisplayMember:
Public Class ListBoxEx
Inherits ListBox
Public Function GetItemValue(item As Object) As Object
Dim index = Me.Items.IndexOf(item)
If (index <> -1 AndAlso Me.DataManager IsNot Nothing) Then
Return Me.FilterItemOnProperty(Me.DataManager.List(index), Me.ValueMember)
End If
Return Nothing
End Function
End Class
If you use that control instead of a regular ListBox then you can do this:
Dim totalOperationsTime As Double
For Each item In ListBoxEx1.SelectedItems
totalOperationsTime += CDbl(ListBoxEx1.GetItemValue(item))
Next
or this:
Dim totalOperationsTime = ListBox1.SelectedItems.Cast(Of Object)().
Sum(Function(item) CDbl(ListBoxEx1.GetItemValue(item)))
One advantage of using that custom control is that you don't have to know what type the data source or its items are. You only have to know that the ValueMember has been set.
I made a few changes to your code. It works with a ListBox. See comments for details.
' "Please Select" doesn't work well in the ListBox, I added it as an option
Private Shared Function GetData(ByVal sql As String, insertPleaseSelect As Boolean) As DataTable
Dim constr As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\hartj\Documents\visual studio 2015\Projects\TIMEMATRIX2.0\TIMEMATRIX2.0\TMX.mdf;Integrated Security=True"
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
If insertPleaseSelect Then
Dim row As DataRow = dt.NewRow()
row(0) = 1
row(1) = "Please Select"
dt.Rows.InsertAt(row, 0)
End If
Return dt
End Using
End Using
End Function
Private Sub MainHome_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
ComboBox1.DataSource = GetData("SELECT [SizeId], [SizeName] FROM [Size]", True)
ComboBox1.DisplayMember = "SizeName"
ComboBox1.ValueMember = "SizeId"
ComboBox2.Enabled = False
ListBox1.SelectionMode = SelectionMode.MultiSimple ' allow multi-select
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
ComboBox2.DataSource = Nothing
ComboBox2.Enabled = False
If ComboBox1.SelectedValue.ToString() <> "0" Then
Dim sql As String = String.Format("SELECT [DetailLevelId], [DetailLevelName] FROM [DetailLevel] WHERE [SizeId] = {0}", ComboBox1.SelectedValue)
ComboBox2.DataSource = GetData(sql, True)
ComboBox2.DisplayMember = "DetailLevelName"
ComboBox2.ValueMember = "DetailLevelId"
ComboBox2.Enabled = True
End If
End Sub
Private Sub ComboBox2_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox2.SelectionChangeCommitted
ListBox1.DataSource = Nothing
ListBox1.Enabled = False
If ComboBox2.SelectedValue.ToString() <> "0" Then
Dim sql As String = String.Format("SELECT [OperationsId], [OperationsName], [OperationsTime] FROM [Operations] WHERE [DetailLevelId] = {0}", ComboBox2.SelectedValue)
ListBox1.DataSource = GetData(sql, False)
ListBox1.DisplayMember = "OperationsName" ' changed this from ValueMember to DisplayMember
ListBox1.ValueMember = "OperationsTime"
ListBox1.Enabled = True
ListBox1.ClearSelected() ' Every time the ListBox is populated, clear it
End If
End Sub
' Added this handler to respond to user input, not programmatic selection changes
Private Sub ListBox1_Click(sender As Object, e As EventArgs) Handles ListBox1.Click
' Here is the sum
Label9.Text = ListBox1.SelectedItems.OfType(Of DataRowView).Sum(Function(o) CType(o("OperationsTime"), Double))
End Sub

Runtime datatable update error

I have a datagridview with a checkbox column. When I click(check/Uncheck) on checkbox field as random, two other fields in corrensponding row should be added OR removed in a datatable (declared runtime).
So that I can do some procedures with data in the datatable.
For that I have declared a datatable as global.
Now the problem is, each time when I click on a checkbox, a simple mouse scrolling is required to update datatable, OR a click needed in the new datagridview which is showing values in the datatable.
My code given below,
global declaration: Public PaymentTable As DataTable
Private Sub ShowOrdersFrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataBind()
Me.DGVOrders.RowsDefaultCellStyle.BackColor = Color.GhostWhite
Me.DGVOrders.AlternatingRowsDefaultCellStyle.BackColor = Color.PaleGoldenrod
PaymentTable = New DataTable()
PaymentTable.Columns.Add("RowId", GetType(Integer))
PaymentTable.Columns.Add("Amount", GetType(Decimal))
End Sub
Private Sub DataBind()
DGVOrders.DataSource = Nothing
DGVOrders.Columns.Clear()
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim dt As New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = "select * from VIEW_PAYMENTS_DUES_BYORDER where CustCode='" & CustCode & "' order by OrderNo DESC"
End With
da.SelectCommand = cmd
da.Fill(dt)
BindingSource1.DataSource = dt
DGVOrders.DataSource = BindingSource1
DGVOrders.ClearSelection()
con.Close()
DGVOrders.Columns(0).Visible = False
DGVOrders.Columns(1).HeaderText = "Order No"
DGVOrders.Columns(2).HeaderText = "Cust Code"
DGVOrders.Columns(3).HeaderText = "Name"
DGVOrders.Columns(4).HeaderText = "Order Date"
DGVOrders.Columns(5).HeaderText = "Order Price"
DGVOrders.Columns(6).HeaderText = "Total Payment"
DGVOrders.Columns(7).HeaderText = "Dues"
For i = 0 To DGVOrders.RowCount - 1
If DGVOrders.Rows(i).Cells(7).Value > 0 Then
DGVOrders.Rows(i).Cells(7).Style.ForeColor = System.Drawing.Color.Red
Else
DGVOrders.Rows(i).Cells(7).Style.ForeColor = System.Drawing.Color.Green
End If
Next
' CHECK BOX
Dim colmnchk As New DataGridViewCheckBoxColumn
colmnchk.DataPropertyName = "chkSelect"
colmnchk.HeaderText = "SELECT"
colmnchk.Name = "chkSelect"
DGVOrders.Columns.Add(colmnchk)
For i = 0 To DGVOrders.RowCount - 1
Next
'CHECK BOX END
End Sub
Private Sub DGVOrders_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVOrders.CellValueChanged
If DGVOrders.Columns(e.ColumnIndex).Name = "chkSelect" Then
Dim checkCell As DataGridViewCheckBoxCell = _
CType(DGVOrders.Rows(e.RowIndex).Cells("chkSelect"), _
DataGridViewCheckBoxCell)
If checkCell.Value = True Then
PaymentTable.Rows.Add(DGVOrders.Rows(e.RowIndex).Cells(0).Value, DGVOrders.Rows(e.RowIndex).Cells(7).Value)
Else
Dim toRemoveID As Integer = DGVOrders.Rows(e.RowIndex).Cells(0).Value
For i = 0 To PaymentTable.Rows.Count - 1
If PaymentTable.Rows(i).Item(0) = toRemoveID Then
PaymentTable.Rows(i).Delete()
Exit Sub
End If
Next
End If
DataGridView1.DataSource = PaymentTable
End If
End Sub
Can sombody to solve the issue, or is there any other good method if my code is wrong ?
Try using a different event like CellContentClick and testing for the ColumnIndex. The drawback with this is the event will fire whenever you click on any cell.
Private Sub DGVOrders_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGVOrders.CellContentClick
'Only interested in the CheckBox column
If e.ColumnIndex = colmnchk.Index Then
Debug.WriteLine("In DGVOrders_CellContentClick for the checkbox")
End If
End Sub

Form.show() does not respond

I am writing a small postIt programm which should enable the user to send little notes to other computers using a database.
I have a main-Form where I can write messages and see users online, a sheet-form which should display messages and a sql database which has a table for users and messages.
The idea is that I am writing messages into the Messagestable and my programm uses SqlDependency to get the new messages and to show them in sheets. So far so good.
The problem is when I add a new Message to my table the SqlDependency fires an Event and my mainForm creates a new sheet which freezes after sheet.Show() is called. The mainForm keeps on running but my sheets always do not respond.
Here's my code:
DBListener:
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Threading
Public Class DBListener
Private changeCount As Integer = 0
Private Const tableName As String = "IMSMessages"
Private Const statusMessage As String = _
"{0} changes have occurred."
Private exitRequested As Boolean = False
Private waitInProgress As Boolean = False
Private recieverHost As String
Private imsMain As IMSMain
Public Sub New(main As IMSMain, recieverHost As String)
Me.imsMain = main
Me.recieverHost = recieverHost
initCommand(recieverHost)
SqlDependency.Start(connectionString)
GetMsg(recieverHost)
End Sub
Private connectionString As String = "Data Source=NB_RANDY\SQLEXPRESS;Initial Catalog=eurom_test;Integrated Security=SSPI;"
Private sqlConn As SqlConnection = New SqlConnection(connectionString)
Private commandMesg As SqlCommand = Nothing
Private commandUsers As SqlCommand = Nothing
Private Sub initCommand(recieverHost As String)
commandMesg = New SqlCommand
commandMesg.CommandText = "SELECT MessageID,SenderHost,RecieverHost,isRead,isRecieved,Stamp from dbo.IMSMessages " &
"WHERE RecieverHost=#RecieverHost" &
" AND isRecieved = 0"
commandMesg.Parameters.Add("#RecieverHost", SqlDbType.VarChar).Value = recieverHost
commandMesg.Connection = sqlConn
commandUsers = New SqlCommand
commandUsers.CommandText = "Select HostName From dbo.IMSUser"
End Sub
Private Sub OnChangeMsg(ByVal sender As System.Object, ByVal e As System.Data.SqlClient.SqlNotificationEventArgs)
Dim dep As SqlDependency = DirectCast(sender, SqlDependency)
RemoveHandler dep.OnChange, AddressOf OnChangeMsg
GetMsg(recieverHost)
End Sub
Private Sub OnChangeUser(ByVal sender As System.Object, ByVal e As System.Data.SqlClient.SqlNotificationEventArgs)
Dim dep As SqlDependency = DirectCast(sender, SqlDependency)
RemoveHandler dep.OnChange, AddressOf OnChangeUser
GetUsers()
End Sub
Public Sub GetMsg(recieverHost As String)
If Not sqlConn.State = ConnectionState.Open Then
sqlConn.Open()
End If
commandMesg.Notification = Nothing
Dim dep As SqlDependency = New SqlDependency(commandMesg)
AddHandler dep.OnChange, New OnChangeEventHandler(AddressOf OnChangeMsg)
Dim table As DataTable = New DataTable
Dim adapter As SqlDataAdapter = New SqlDataAdapter(commandMesg)
adapter.Fill(table)
imsMain.recieveNewMessages(table)
End Sub
Public Sub GetUsers()
If Not sqlConn.State = ConnectionState.Open Then
sqlConn.Open()
End If
commandMesg.Notification = Nothing
Dim dep As SqlDependency = New SqlDependency(commandUsers)
AddHandler dep.OnChange, New OnChangeEventHandler(AddressOf OnChangeUser)
Dim table As DataTable = New DataTable
imsMain.updateOnlineUserList()
End Sub
End Class
IMSMain-Form:
Imports System.Data.SqlClient
Imports System.Threading
Public Class IMSMain
Private user As IMSUser
Private listener As DBListener
Private sqlConn As SqlConnection
Public Sub New()
InitializeComponent()
sqlConn = New SqlConnection("Data Source=NB_RANDY\SQLEXPRESS;Initial Catalog=eurom_test;Integrated Security=SSPI;")
Me.user = New IMSUser(My.Computer.Name)
user.register()
updateOnlineUserList()
listener = New DBListener(Me, user.HostName)
End Sub
Private Sub onSend(sender As Object, e As EventArgs) Handles bt_send.Click
Dim command As SqlCommand = New SqlCommand
Dim msgText = tb_text.Text
Dim reciever As IMSUser = lb_Online.SelectedItem
Dim insert_string As String = "Insert INTO dbo.IMSMessages(Text,RecieverHost,SenderHost,isRead,isRecieved,Stamp) Values(#Text,#RecieverHost,#SenderHost,#isRead,#isRecieved,#Stamp)"
Dim adapter As SqlDataAdapter = New SqlDataAdapter
Dim table As DataTable = New DataTable()
Try
If Not sqlConn.State = ConnectionState.Open Then
sqlConn.Open()
End If
command.Connection = sqlConn
command.CommandText = insert_string
adapter.SelectCommand = command
adapter.Fill(table)
command.CommandText = insert_string
command.Parameters.Add("#Text", SqlDbType.VarChar).Value = msgText
command.Parameters.Add("#RecieverHost", SqlDbType.NChar).Value = reciever.HostName
command.Parameters.Add("#SenderHost", SqlDbType.NChar).Value = user.HostName
command.Parameters.Add("#isRecieved", SqlDbType.Bit).Value = 0
command.Parameters.Add("#isRead", SqlDbType.Bit).Value = 0
command.Parameters.Add("#Stamp", SqlDbType.SmallDateTime).Value = DateTime.Now
command.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine("onSend: internal database exception" + ex.Message)
End Try
End Sub
Private Sub processMessageId(refMessageID As Integer)
Dim command As SqlCommand = New SqlCommand
Dim msgID_string As String = "SELECT * from dbo.IMSMessages " &
"WHERE MessageID=#MessageID AND isRecieved = 0" &
" ORDER BY Stamp"
Dim isRecievedUpdate_string As String = "Update dbo.IMSMessages " &
"SET isRecieved=1" &
" WHERE MessageID=#MessageID"
Dim adapter As SqlDataAdapter = New SqlDataAdapter
Dim table As DataTable = New DataTable()
Try
If Not sqlConn.State = ConnectionState.Open Then
sqlConn.Open()
End If
command = New SqlCommand
command.CommandText = msgID_string
command.Parameters.Add("#MessageID", SqlDbType.Int).Value = refMessageID
command.Connection = sqlConn
adapter.SelectCommand = command
adapter.Fill(table)
command = New SqlCommand
command.Connection = sqlConn
command.CommandText = isRecievedUpdate_string
command.Parameters.Add("#MessageID", SqlDbType.Int).Value = refMessageID
command.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine("processMessageID: internal database exception" + ex.Message)
End Try
Try
Dim row As DataRow = table.Rows(0)
Dim senderHost As String = row("SenderHost")
Dim sender As IMSUser = New IMSUser(senderHost)
Dim currentSheet As IMSSheet
Dim stringText As String = row("Text")
Dim stamp As Date = row("Stamp")
currentSheet = New IMSSheet(sender, stringText, stamp)
currentSheet.Show()
Catch ex As Exception
Console.WriteLine("processMessageID: error while showing sheet")
End Try
End Sub
Public Sub recieveNewMessages(newMessageTable As DataTable)
For Each row As DataRow In newMessageTable.Rows
Dim id As Integer = row("MessageID")
processMessageId(id)
Next
End Sub
Public Sub updateOnlineUserList()
lb_Online.Items.Clear()
Dim adapter As SqlDataAdapter = New SqlDataAdapter
Dim table As DataTable = New DataTable()
Dim command As SqlCommand = New SqlCommand
Dim onlineUser_string = "Select * FROM dbo.IMSUser"
command.CommandText = onlineUser_string
Try
If Not sqlConn.State = ConnectionState.Open Then
sqlConn.Open()
End If
command.Connection = sqlConn
adapter.SelectCommand = command
adapter.Fill(table)
Catch ex As Exception
Console.WriteLine("internal database exception" + ex.Message)
End Try
For Each row As DataRow In table.Rows
Dim tmp As IMSUser = New IMSUser(row("HostName"))
If Not user.Equals(tmp) Then
lb_Online.Items.Add(tmp)
End If
Next
End Sub
End Class
IMSSheet-Form:
Public Class IMSSheet
Dim IsDraggingForm As Boolean = False
Private MousePos As New System.Drawing.Point(0, 0)
Public Sub New(session As IMSUser, text As String, stamp As Date)
Ini
tializeComponent()
Me.tb_sender.Text = session.HostName
addText(text, stamp)
End Sub
Private Sub addText(msg As String, stamp As DateTime)
Dim currentText As String = tb_text.Text
currentText = currentText + stamp.ToString + Environment.NewLine + msg + Environment.NewLine
tb_text.Text = currentText
End Sub
Private Sub IMSSheet_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseDown
If e.Button = MouseButtons.Left Then
IsDraggingForm = True
MousePos = e.Location
End If
End Sub
Private Sub IMSSheet_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseUp
If e.Button = MouseButtons.Left Then IsDraggingForm = False
End Sub
Private Sub IMSSheet_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseMove
If IsDraggingForm Then
Dim temp As Point = New Point(Me.Location + (e.Location - MousePos))
Me.Location = temp
temp = Nothing
End If
End Sub
Private Sub onClose(sender As Object, e As EventArgs) Handles bt_Close.Click
Me.Close()
End Sub
Private Sub bt_minimize_Click(sender As Object, e As EventArgs) Handles bt_minimize.Click
Me.WindowState = FormWindowState.Minimized
End Sub
Private Sub bt_Close_MouseHover(sender As Object, e As EventArgs) Handles bt_Close.MouseHover
End Sub
Private Sub bt_minimize_MouseHover(sender As Object, e As EventArgs) Handles bt_minimize.MouseHover
End Sub
End Class
Interesting is that if I have already some new Messages in my Messagestable before I run the programm they are going to be displayed correctly.
If I display the sheets using Form.ShowDialog() it works as well but its not how I want it to work.
As I am out of ideas I hope you can help me.
You are running into issues because the change event of SqlDependency occurs on a different thread that your UI thread. From the SqlDepending documentation:
The OnChange event may be generated on a different thread from the
thread that initiated command execution.
When calling sheet.Show() on a non UI thread, Show() will lockup because there is no message loop to handle the UI events. Use Invoke() on ImsMain to create and show the ImsSheet on your UI thread.

How to get the value of DataGridView.SelectedRows().Cells() from different forms?

I have 2 forms and within each of the 2 forms there is a DataGridView(chatform and prodetail).
In the chatform I created a DataGridView which has a generated Button in each row.
Each Button when clicked will load a prodetail form and when in the prodetail form I want to get the value of the SelectedRow.Cell from the DataGridView in the originating chatform.
Code (chatform):
Public Sub loadtoDGV()
Dim sqlq As String = "SELECT * FROM chattbl"
Dim sqlcmd As New SqlCommand
Dim sqladpt As New SqlDataAdapter
Dim tbl As New DataTable
With sqlcmd
.CommandText = sqlq
.Connection = conn
End With
With sqladpt
.SelectCommand = sqlcmd
.Fill(tbl)
End With
DataGridView1.Rows.Clear()
For i = 0 To tbl.Rows.Count - 1
With DataGridView1
.Rows.Add(tbl.Rows(i)("Username"), tbl.Rows(i)("Title"), tbl.Rows(i)("ChatDateTime"))
End With
Next
conn.Close()
End Sub
Private Sub ChatForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
loadtoDGV()
End Sub
Code (DataGridView1.CellContentClick):
Private Sub grdData_CellContentClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim colName As String = DataGridView1.Columns(e.ColumnIndex).Name
If colName = "Detail" Then
Prodetail.Show()
MessageBox.Show(String.Format("You clicked the button in row {0} of the Detail column", e.RowIndex))
End If
End Sub
Code (prodetail):
Public Sub loadtoDGV2()
Dim i As Integer
i = ChatForm.DataGridView1.SelectedRows.Count
MsgBox(i)
Dim compareai As String = ChatForm.DataGridView1.SelectedRows(i).Cells(1).Value
Dim sqlq As String = "SELECT * FROM Chattbl WHERE Title =" & compareai & ""
Dim sqlcmd As New SqlCommand
Dim sqladpt As New SqlDataAdapter
Dim tbl As New DataTable
With sqlcmd
.CommandText = sqlq
.Connection = conn
End With
With sqladpt
.SelectCommand = sqlcmd
.Fill(tbl)
End With
DataGridView1.Rows.Clear()
For i = 0 To tbl.Rows.Count - 1
With DataGridView1
.Rows.Add(tbl.Rows(i)("Username"), tbl.Rows(i)("Title"), tbl.Rows(i)("ChatDateTime"), tbl.Rows(i)("ChatContent"))
End With
Next
conn.Close()
End Sub
Private Sub Prodetail_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
loadtoDGV2()
End Sub
What have I done wrong?
I tried to use MsgBox(i) i = SelectedRow(0) assuming it would show the data for first row, but DataGridView1 in prodetail does not load any data from the database.
I did not observe any errors, I just don't have a solution.
The first problem is you are calling the class instead of an instance. VB.NET will allow you to call an instance of the form as its name, but it will be the same instance across every use. I would not suggest doing this.
To start I would change this:
Private Sub grdData_CellContentClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim colName As String = DataGridView1.Columns(e.ColumnIndex).Name
If colName = "Detail" Then
Prodetail.Show()
MessageBox.Show(String.Format("You clicked the button in row {0} of the Detail column", e.RowIndex))
End If
End Sub
To this:
Private Sub grdData_CellContentClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim colName As String = DataGridView1.Columns(e.ColumnIndex).Name
If colName = "Detail" Then
Dim newDetailForm as new Proddetail(dataGridView1.Rows(e.RowIndex).Cells(1).Value)
newDetailForm.show()
MessageBox.Show(String.Format("You clicked the button in row {0} of the Detail column", e.RowIndex))
End If
End Sub
Then in the Proddetail class you need to add a constructor and a member like this:
Private SearchValue as String
Public Sub New(byval theSearchValue as string)
InitalizeComponent()
SearchValue = theSearchValue
End Sub
Then in your load routine:
Public Sub loadtoDGV2()
Dim sqlq As String = "SELECT * FROM Chattbl WHERE Title =" & SearchValue & ""
Dim sqlcmd As New SqlCommand
Dim sqladpt As New SqlDataAdapter
Dim tbl As New DataTable
With sqlcmd
.CommandText = sqlq
.Connection = conn
End With
With sqladpt
.SelectCommand = sqlcmd
.Fill(tbl)
End With
DataGridView1.Rows.Clear()
For i = 0 To tbl.Rows.Count - 1
With DataGridView1
.Rows.Add(tbl.Rows(i)("Username"), tbl.Rows(i)("Title"), tbl.Rows(i)("ChatDateTime"), tbl.Rows(i)("ChatContent"))
End With
Next
conn.Close()
End Sub
This should then display the details of the clicked row in a new instance of the Proddetail class.
I added a custom paramaterized constructor to the class that takes the value for the SQL query string. This way when you create a new instance of the form in your code, you can always pass in the search string that would lead to the details you want to view.