How to run code in real time across multiple tabs, windows form, vb.net - vb.net

I am currently programming in vb.net for a windows forms applications.
I have a windows form with multiple tabs and within each tab I have a DGV. Each DGV is connected to an sql server table, the same table across all tabs.
I want to use a check box to copy rows of data from the sql table to a specific tab. In this case I want to try and have this happen in real time, so without using a "refresh" button or something like that.
On each row in every tab I want the row of data to appear or disappear from the last tab depending on the status of the check box.
I have attached code and a picture. The code is used on the form load event to load the tables into the tabs. In the image you can see i want the rows to be loaded into the "ordered floors" tab after the check box has been checked.
Private Sub FormOrdered_Load(sender As Object, e As EventArgs) Handles Me.Load
'load line 2 tab
Try
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("Select LineNumber, ShearNumber, JobNumber, FloorNumber, OrderedBy, DateOrdered, Ordered FROM Production.dbo.tblFCordered where LineNumber = 2", conn1)
Dim da As New SqlDataAdapter
da.SelectCommand = comm1
da.Fill(Line2)
End Using
conn1.Close()
End Using
DataGridLine2.DataSource = Line2
Catch ex As Exception
MsgBox("Unable to make SQL Connection to load Line 2 Table, please contact an engineer!")
MsgBox(ex.ToString)
End Try
image

You could just clone the rows from the DGV when you check the checkbox and add them to the Ordered floors dgv.
Something like:
Private Sub CopyRows_CheckedChanged() Handles CopyRows.CheckedChanged
For each r as DataGridViewRow in MyDGV.Rows
dgvOrderedFloors.Rows.Add(r.Clone())
next
End Sub
You'll have to modify this to suit obviously, but I think something along these lines should do what you want.
Or you could clone the data tables you use for each datagridview, and add them to one master table which will be the datasource for your Ordered floors datagridview.
That would be better, but might be more work upfront.

Related

How to read an Access database column into an array with VB.NET?

There's already a question like this but its in VBA, and I need VB.NET
I'm trying to get the contents of a column then put them in an array or something so I can then put the data into the items of a ComboBox. If anyone can suggest a better way, id love to know. This is the code I am using right now:
sql = "SELECT Firstname FROM Candidates WHERE Position='President'"
cmd = New OleDbCommand(sql, cn)
dr = cmd.ExecuteReader
So, first lets build the connection to the Access DB.
So, from the menu go project -> "my project name" properties
(last option).
This:
So, in above we hit the [...] button (connection builder).
Then this:
and then:
then use browse to select the Access database file.
If this is a "mdb" file, then we use JET, but for accDB, we have to choose/use
ACE.
So, after selecting the access file, then hit advanced:
this:
Now, it should default to ACE, but MAKE SURE you check this!!!
This:
If you don't see "ACE" in that list, then you not be able to use/open a accDB file, but can use JET to open mdb files.
Keep in mind, that if you are using vs2022?
Then the test connection button will ALWAYS fail, but if you run your project/code, it should work.
Note that you ALSO MUST force your project to x86 if you using/have Access x32 bits.
So, that is this option:
If you don't have/see a x86 option, then use the configeration manager, and create a x86 choice. You MUST do this!!
Ok, so now we have our connection built.
So, on a form, lets drop in a button to "load" the combo box, drop in a combo box.
And lets even drop in a button to show how to get/grab/use a value the user selected.
Now, a combo box can (often) have two columns. one column is "hidden", and the other is for display.
So, in our example, we will fill out the combo box with a list of hotels from the database, and we will use both columns.
"id" - that is the database primary key value - it will be hidden, not display.
"HotelName" that is the column from the database to display in the combo box.
So, in the combo box property sheet, set:
ValueMember to ID
DisplayMember to HotelName (or your column to display).
So, the code for loading the combo box will look like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strSQL As String =
"SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName"
cboHotels.DataSource = MyRst(strSQL)
End Sub
Function MyRst(strSQL As String) As DataTable
Dim rstData As New DataTable
Using conn As New OleDbConnection(My.Settings.AccessDB)
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
And our button code to test get/grab/see the selected value is this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Label2.Text = "Hotel Select = " & cboHotels.Text &
" value = " & cboHotels.SelectedValue
End Sub
Note how we are able to get the 2 values fro the combo box (the database primary key "value") and also the text (hotel name).
So, final result is this:

How do I make DataBindings update in runtime?

Noob programmer here, go easy on me if the answer was straight up obvious. Couldn't really find the right title but it's the closest one I got.
To get straight to the point, I have a textbox in my program, and whatever I type in the textbox should go straight to a table in my database, and then when I click a specific button, whatever I last put in the table should show up on the label beside the textbox via DataBindings (at least, that's how I want it to go).
It works for the most part. When I type something in and click my button, the text shows up on the label. But when I do it a second time , the label doesn't update to what I last typed (it only updates when I stop and start running the program again.)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connection.Open()
Dim test1 As String = "SELECT TOP 1 Letters From NewTable ORDER BY Id DESC"
ExecuteQuery(test1)
Dim command As New SqlCommand(test1, connection)
Dim adapter As New SqlDataAdapter(test1, connection)
adapter.Fill(TestDatabaseAgainDataSet1, "NewTable")
randomlabel.DataBindings.Clear()
randomlabel.DataBindings.Add("Text", TestDatabaseAgainDataSet1.NewTable, "Letters")
command.ExecuteNonQuery()
connection.Close()
End Sub
I know there are some easier ways for user-generated text to show up on a label, but I kinda need it so the last thing I typed is still there when I click the button.
If I understand correctly, you only have problem on the second part of your project: whatever you last put in the table should show up on the label beside the textbox.
If you are on SQL Server you can use SqlDataReader class that provides a way of reading a forward-only stream of rows from a SQL Server database.
Dim cmdLastLetter As SqlCommand = conn.CreateCommand()
cmdLastLetter.CommandText = "SELECT TOP 1 Letters From NewTable ORDER BY Id DESC"
Dim drLastLetter As SqlDataReader = cmdLastLetter.ExecuteReader()
If drLastLetter.Read() Then
Me.Label1.Text = drLastLetter("Letter")
End If
drLastLetter.Close()
cmdLastLetter.Dispose()
If you are using another database consult this document: you have to use another class but the concept is the same.

Display data in combobox from one winform to another winform

I have this form1 that displays a list of my entries. When I want to update an entry, I will click it in the DataGridView and an update button will be visible. Once I clicked the 'Update' button, form2 will appear and the details of the currently selected row in my dgv will be listed.
My problem is that one of the details involves a data from a combobox. It does not change the value.
This form2 acts as a form to create entries and at the same time to update them. I load the details to this form as is like you are creating one but I am updating them.
Now this combobox has data that has been loaded from the database. Something like this:
Dim cmd2 As New MySqlCommand
Dim dt2 As New DataTable
con.Open()
With cmd2
.Connection = con
.CommandText = "Select staff_name from staff where staff_position='Pre-seller'"
End With
da.SelectCommand = cmd2
da.Fill(dt2)
With cmbseller
.DataSource = dt2
.DisplayMember = "staff_name"
.ValueMember = "staff_name"
End With
con.Close()
All is well, until I need to update an entry. The data in the combo box is not changing from the details of my currently selected row.
For example, the data in the entry for this combobox is 'Leizel', but when I click the update to show form2, it shows a different item. Like the one that has been loaded from the database. It is not adjusting to what I want. I change the other details but not this one.
Can anyone suggest anything?
EDIT:
This is the code I am using in loading data from form1 to form2. obviously this is only a part of it.
Dim frm3 As New SalesOrder
frm3.cmbseller.Text = DataGridView1.Item(2, DataGridView1.CurrentRow.Index).Value
where 2 is the column in my dgv that needs to be displayed in the combobox in form2.

DataGridView does not update after delete, update or insert

I have a DatagGridView which has a DataSet from an Access database. I have a problem when I delete, update or insert data.
This is an example from my update method.
Private Sub btnactualizar_Click(sender As Object, e As EventArgs) Handles btnactualizar.Click
novacios()
Try
con = New OleDb.OleDbConnection(ruta)
con.Open()
Dim actualiza As String = "UPDATE Usuarios SET nombre_real=#a1, correo = #a2, pass = #a3, activo = #a4 WHERE Correo = #a5"
sentencia = New OleDb.OleDbCommand(actualiza)
sentencia.Connection = con
sentencia.Parameters.AddWithValue("#a1", txtusuarios.Text)
sentencia.Parameters.AddWithValue("#a2", txtmail.Text)
sentencia.Parameters.AddWithValue("#a3", txtpass.Text)
sentencia.Parameters.AddWithValue("#a4", txtactivo.Text)
sentencia.Parameters.AddWithValue("#a5", txtusuarios.Text)
sentencia.ExecuteReader()
con.Close()
MessageBox.Show("Actualización realzada con éxito", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information)
Me.UsuariosTableAdapter.Fill(Me.Bd_proyectoNDataSet.Usuarios)
limpiatextos()
Catch ex As Exception
ex.Message.ToString()
End Try
End Sub
As we can see after the messagebox, the list should be updated with the fill method. But the datagrid is still the same.
Here some pictures to understand what I'm talking about. I will appreciate any help.
Before updating the data
After updating the data. Nothing happened
You're doing things backwards. Don't make a change to the database and then try to update the grid from there. You update the local data first and then save that change to the database.
Your grid is bound to a BindingSource and that is bound to a DataTable in your typed DataSet. That's where you should be making the change. It may be that you should be binding your TextBoxes to the same data, in which case the modifications to the data would happen automatically. If not then you should be copying the data from the TextBoxes back into the typed DataRow you're editing. That grid will automatically reflect that change. YOu then call Update on your table adapter to save those changes from the DataTable back to the database.
In short, don't make changes directly to the database and then try to pull those changes from the database into your local data. Make the changes to the local data first, then save those changes to the database.

Open Form faster & remove "System.Data.DataRowView" flicker from Combobox data binding

I have plenty Comboboxes on my form (around 20), and all of them are displaying items from different tables of my DB. If I put all code on Form_Load event then Form opens very slow. So I tried to paste code in different varieties, and currently I'm stuck at Combobox_Enter event - now Form loads fast, but when I click on drop-down of combobox I see sometimes "System.Data.DataRowView" flickering before items are loaded in Combobox. Is there any way to achieve both - fast Form opening & Combobox loading Items without flickering ?....So far I tested with Form_Activate,Form_GotFocus(not working) and Combobox_GotFocus,Combobox_MouseHover,Combobox_Click(not exactly perfect). This is an example of how I bind my Comboboxes:
Private Sub Combobox1_Enter(sender As Object, e As EventArgs) Handles Combobox1.Enter
Dim SQL As String = "SELECT Name from MyTable"
Dim dtb As New DataTable()
Using con As OracleConnection = New OracleConnection("Data Source=MyDB;User Id=Lucky;Password=MyPassword;")
Try
con.Open()
Using dad As New OracleDataAdapter(SQL, con)
dad.Fill(dtb)
End Using
Combobox1.DataSource = dtb
Combobox1.DisplayMember = "Name"
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
Combobox1.SelectedIndex = -1
End Using
End Sub
I also tried with declaring " Public con As OracleConnection", but output is same as I have It now.
Any help appreaciated !
When binding a ComboBox or the like, you should pretty much ALWAYS set the DataSource last. You are not and that's why you see "System.Data.DataRowView" displayed.
When you bind a list to a ComboBox, the control will display data from the column or property specified in the DisplayMember if there is one, otherwise it will call ToString on each item. In your code, you first set the DataSource and, at that point, the DisplayMember is not set so the control calls ToString on each item. The result of that is "System.Data.DataRowView". When you then set the DisplayMember, those values that the control just went to the trouble of generating and displaying are discarded and the DisplayMember is used to get new values.
Even if you weren't seeing that effect, you'd still be wasting your control's time generating values that you don't want. ALWAYS set the DisplayMember, ValueMember or the like before setting the DataSource in code unless you have a specific reason not to. The only reason that I'm aware of is when you're binding a CheckedListBox, which has an issue when DataSource is set last.
By the way, shouldn't you have a test there to only retrieve data if there is no data already loaded? You don't want to reload data if the user returns to the same control, do you?