VB.Net - Entry in datagridview keeps duplicating on event - vb.net

Here is my code, everytime I click the Button1, instead of refreshing the Datagridview, it only adds another entry that is a duplicate of the previous one. I know I'm missing something in my code that will clear the data in Datagrid before loading it again. Please help..
Private Function LoadData_UnitProcess()
Dim UP_SQL As String = "SELECT LotNum FROM Transactions WHERE StatusID=3 ORDER BY Process_EntryDate DESC"
Dim UP_Ad As OleDbDataAdapter = New OleDbDataAdapter(UP_SQL, strCon)
UP_Ad.Fill(UP_Ds, "Transactions")
UnitOnProcess_DG.DataSource = UP_Ds.Tables(0)
With UnitOnProcess_DG
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Lot #"
.Columns(0).Width = "363"
.AllowUserToAddRows = False
End With
LoadData_UnitProcess = ""
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
LoadData_UnitProcess()
End Sub
Private Sub Displayer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadData_UnitProcess()
End Sub

You dataset UP_Ds is probably a property or field. You need to reset the dataset before filling it again, otherwise the content is appended to the previous.
UP_Ds.Reset()
UP_Ad.Fill(UP_Ds, "Transactions")
UnitOnProcess_DG.DataSource = UP_Ds.Tables(0)

Related

How do I load a form inside another form?

I created a registration form and added a form with features "Update, Delete, Refresh," along with a DataGridView to show data from the registration form.
Here's my form:
Since I inserted a TreeView, when I click the Update button as in the picture, I get the error:
Object Reference Not set to an instance of an object
I think my code in the TreeView form is wrong.
This is what I entered:
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
If e.Node.Text = "Update/Delete Student" Then
Dim regstu As New Registered_Students
regstu.MdiParent = Me
regstu.Show()
End If
End Sub
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
If e.Node.Text = "Update/Delete Student" Then
Dim regstu As New Registered_Students
Form_father.IsMdiContainer = True
Form_father.TopLevel = False
regstu.MdiParent = New Form_father
Form_father.Panel1_Container.Controls.Add(regstu)
regstu.Show()
End If
End Sub

Create list box in runtime and change its color via menu in runtime

I need to write this small program in visual basic, but i face a problem which is i can't change the color or add list form text file during runtime.
this is picture of what i wont to do
http://i62.tinypic.com/30tghh0.png
And this is the code i wrote so far,,
Public Class Form1
Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click
Dim listBox1 As New System.Windows.Forms.ListBox
listBox1.Text = "New List"
listBox1.Location = New Point(25, 25)
listBox1.Size = New Size(380, 280)
Me.Controls.Add(listBox1)
OpenToolStripMenuItem.Enabled = True
SaveToolStripMenuItem.Enabled = True
SaveAsToolStripMenuItem.Enabled = True
CloseToolStripMenuItem.Enabled = True
EditToolStripMenuItem.Enabled = True
End Sub
Private Sub ExirToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExirToolStripMenuItem.Click
End
End Sub
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
If (OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
Dim myfile As String = OpenFileDialog1.FileName
Dim allLines As String() = File.ReadAllLines(myfile)
For Each line As String In allLines
ListBox1.Items.Add(line)
Next
End If
End Sub
End Class
The problem as you see is in OpenToolStripMenuItem sub with line ListBox1.Items.Add(line)
is there is no listbox1 because is not created yet.the same with color, save and the rest.
so, please help me to solve it.
Move the declaration of ListBox1 out to the Class level:
Public Class Form1
Private ListBox1 As System.Windows.Forms.ListBox
Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click
ListBox1 = New System.Windows.Forms.ListBox
...
End Sub
...
End Class
*But why create it at run-time like this? You could add it at design-time and set the Visible() property to False. When the New button is clicked, you change Visible() to True. Unless you need a new ListBox to be created each time so you have more than one? If so, how will they be laid out?...

Listbox selected item to textbox in Vb.net

Sometimes simple code will make us big confusion. I researched this questions in internet from past few hours.
I have a listbox, data will load from Access table. When i selected an item in listbox, i wanted to show that item in a textbox.
i have tried some code as below, nothing worked for me:
Private Sub listBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
For i As Integer = 0 To listBox1.SelectedItems.Count - 1
textBox1.Text &= DirectCast(listBox1.SelectedItems(i), DataRowView)(1).ToString & vbCrLf
Next
End Sub
Private Sub listBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
textBox1.Text = listBox1.SelectedItem.Value
End Sub
Here is the code that will give values to listbox from access table
Dim dataAdapter As New OleDbDataAdapter("select * from eval", connection)
Dim ds As DataSet = New DataSet
dataAdapter.Fill(ds, "eval")
listBox1.DataSource = ds
listBox1.DisplayMember = "eval"
listBox1.ValueMember = "eval.eval"
textbox1.Text = listBox1.GetItemText(listBox1.SelectedItem);
Here is a simple example of what you can do. Lets say you have a list box with 4 items: VB.Net,C#,Java and Python. First, make the listbox SelectionMode = MultiSimple. If I understood you correctly, you want all the items that have been selected in the listbox to be transfered to a text box. You can do that by wrtining this code:
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox1.Clear()
For Each Item As Object In ListBox1.SelectedItems
TextBox1.AppendText(Item.ToString + Environment.NewLine)
Next
End Sub
Here are the results :
(Sorry for the bad quality)
The listBox1.SelectedItem will give you back a System.Data.Datarow, because that is what you put in there. If you want to display the same text in the textbox that is displayed for the listbox, you can simply use this:
Private Sub listBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
textBox1.Text = listBox1.text
End Sub
If you want a value from another field (you do not show your fields so lets pretend there is one called "FirstName") you could do this:
Private Sub listBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
Dim DR as datarow = listBox1.SelectedItem
textBox1.Text = DR("FirstName")
End Sub

Resize UserControls in every instance of TabPage

This has been killing me for a couple of weeks now. I have a browser that I've made and it's using a TabControl. Every time the TabPage "+" is clicked, a new one is added. Each one of these TabPages has userControls (WebBrowser, Address Bar, Back Button, Forward Button, etc..). When the user resizes Form1, I want all userControls to fit to the TabPage/Form1.
Basically, I want my userControls to fit the current size of the Form but I can't figure it out. Right now, I have the TabControls working but that was done by simply using the Anchor property. That option isn't avialable for the UserControls. I manually anchored it programatically but it doesn't resize. It just sticks everything right in the middle with the smaller size....
here's the Code:
'THIS IS THE CODE FOR THE FORM
Imports System.IO
Public Class Form1
'The Global Variables
Dim theControls1 As New theControls
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TabPage1.Controls.Add(theControls1)
theControls1.theBrowser.Navigate("http://google.com")
End Sub
Private Sub Form1_SizeChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.SizeChanged
'For Auto Sizing theControls to Form1
theControls1.Width = TabControl1.Width - 8
theControls1.Height = TabControl1.Height - 25
End Sub
Private Sub TabControl1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.Click
'Add new tab with the same controls.
Dim theNewTab As New TabPage
Dim theOtherControls As New theControls
Dim theTabCounter As Integer = TabControl1.TabPages.Count
theOtherControls.AutoSize = True
theOtherControls.Width = TabControl1.Width
theOtherControls.Height = TabControl1.Height
theOtherControls.Anchor = AnchorStyles.Right & AnchorStyles.Left & AnchorStyles.Bottom & AnchorStyles.Top
Dim theSelectedTab As String = TabControl1.SelectedTab.Text
If theSelectedTab = "+" Then
TabControl1.TabPages.Insert(theTabCounter - 1, theNewTab)
theNewTab.Controls.Add(theOtherControls)
theControls1.theBrowser.Navigate("http://google.com")
theOtherControls.theBrowser.Navigate("http://google.com")
TabControl1.SelectTab(theTabCounter - 1)
End If
End Sub
End Class
'THIS IS THE CODE FOR THE USERCONTROLS
Imports System.IO
Imports System.Data.OleDb
Public Class theControls
'The History Database Connection String
Dim theHistoryDatabaseConn As New OleDbConnection
Private Sub ComboBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles theAddressBar.KeyDown
'Navigate to Webpage stated in theAddressBar
If e.KeyValue = Keys.Enter Then
theBrowser.Navigate(theAddressBar.Text)
e.SuppressKeyPress = True
End If
End Sub
Private Sub goForward_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles goForward.Click
theBrowser.GoForward()
End Sub
Private Sub goBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles goBack.Click
theBrowser.GoBack()
End Sub
Private Sub theBrowser_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles theBrowser.DocumentCompleted
'Set Tab Text to current web page and Address Bar
Form1.TabControl1.SelectedTab.Text = theBrowser.Url.Host.ToString
Me.theAddressBar.Text = Me.theBrowser.Url.AbsoluteUri.ToString
'Read the History
theHistoryDatabaseConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Marc Wilson\Documents\Visual Studio 2010\Projects\myBrowser\myBrowser\bin\Debug\TheHistoryDB.accdb"
theHistoryDatabaseConn.Open()
'Populate theAddressBar with the contents from the History
theAddressBar.Items.Clear()
Dim readTheHistory As String
Dim getTheHistory As OleDbCommand
readTheHistory = "SELECT [Host Name] FROM TheHistory"
getTheHistory = New OleDbCommand(readTheHistory, theHistoryDatabaseConn)
Dim theData As New OleDbDataAdapter(getTheHistory)
Dim theTable As New DataTable("TheHistory")
'theHistoryDatabaseConn.Open()
theData.Fill(theTable)
For Each row As DataRow In theTable.Rows
theAddressBar.Items.Add(row.Item("Host Name"))
Next
'Writes history to TheHistory Database (No Duplicates!)
If theAddressBar.Items.Contains(theBrowser.Url.Host.ToString) Then
Else
'Write The History
Dim writeTheHistory As OleDbCommand = New OleDbCommand("INSERT INTO TheHistory ([Host Name], [Absolute Path]) VALUES (theBrowser.URL.Host.ToString, theBrowser.URL.AbsoluteUri.ToString)", theHistoryDatabaseConn)
writeTheHistory.Parameters.Add("#Host Name", OleDbType.Char, 255).Value = theBrowser.Url.Host.ToString
writeTheHistory.Parameters.Add("#Absolute Path", OleDbType.Char, 255).Value = theBrowser.Url.AbsoluteUri.ToString
theHistoryDatabaseConn.Close()
theHistoryDatabaseConn.Open()
writeTheHistory.ExecuteNonQuery()
theHistoryDatabaseConn.Close()
End If
theHistoryDatabaseConn.Close()
End Sub
Private Sub theBrowser_ProgressChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserProgressChangedEventArgs) Handles theBrowser.ProgressChanged
'Status Bar Text
Label1.Text = theBrowser.StatusText.ToString
End Sub
Private Sub theAddressBar_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles theAddressBar.SelectedValueChanged
Me.theBrowser.Navigate(Me.theAddressBar.Text)
End Sub
End Class
Whenever you create an instance of your UserControl, set its Dock() property to Fill:
Dim theOtherControls As New theControls
theOtherControls.Dock = DockStyle.Fill

Winforms ListBox Control Not Updating After Source Changes

I have a ListBox (LB) with a DataTable (DT) DataSource in the Form Class globally populated in the Form_Load event.
Private Sub frmEditPresets_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
DT.Columns.Add("DisplayText")
DT.Columns.Add("PresetID")
For Each TSI As ToolStripItem In Presets.DropDownItems
If TSI.Name.IndexOf("preset_") > -1 Then
DT.Rows.Add(TSI.Text, TSI.Name)
End If
Next
LB.DataSource = DT
LB.DisplayMember = "DisplayText"
End Sub
When I use my Rename button. It updates the menu item and the Data Source but the Listbox doesn't refresh until I click another item in the listbox.
Rename code:
Private Sub btnRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRename.Click
Dim R As DataRowView = LB.SelectedItem
Dim S As String = InputBox("Preset Name", "Rename", R("DisplayText"))
If S.Trim.Length = 0 Then Exit Sub
If Presets.DropDownItems.ContainsKey(R("PresetID").ToString) Then
Presets.DropDownItems(R("PresetID").ToString).Text = S
End If
R("DisplayText") = S
End Sub
I'm sure this is a simple question with a simple answer but I can't seem to figure it out. I've tried Refresh(). I've tried setting the DataSource again. I read this StackOverflow question Winforms listbox not updating when bound data changes but ResetBindings() doesn't seem to be an available method in this context.
*Edit. I gave Steve credit for the answer as he mentioned BindingContext. Although, that led me to find BindingContext(DT).EndCurrentEdit() which updated my LB display and maintained the selection.
Tried with this, and it works.....
Private Sub btnRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRename.Click
Dim R As DataRowView = LB.SelectedItem
Dim S As String = InputBox("Preset Name", "Rename", R("DisplayText"))
If S.Trim.Length = 0 Then Exit Sub
If Presets.DropDownItems.ContainsKey(R("PresetID").ToString) Then
Presets.DropDownItems(R("PresetID").ToString).Text = S
End If
R("DisplayText") = S
BindingContext(DT).EndCurrentEdit()
End Sub