VB: Populate a textbox with popup from txt - vb.net

I am creating a vb file, and I have a txt file with some that I want to populate a textbox.
What it is currently doing: It is choosing an option that i input in the textbox that I have created.
What I want it to do: Create a popup with every option from a textbox file, show it on screen, let me choose, and then populate another textbox with my choice.
Current code and screenshot:
Public Class Form1
Private Sub TextBox1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseClick
Dim f As New Form2
Try
f.Owner = Me
'
' Before showing the child form populate TextBoxes
'
f.TextBox1.Text = "1"
f.TextBox2.Text = "2"
f.TextBox3.Text = "3"
If f.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim Box = (From T In f.Controls.OfType(Of TextBox)()
Where Not String.IsNullOrWhiteSpace(T.Text)
Select T Order By T.Name).FirstOrDefault
If Box IsNot Nothing Then
Me.TextBox1.Text = Box.Text
End If
End If
Finally
f.Dispose()
End Try
End Sub
End Class
Form 2
Public Class Form2
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim Box = (From T In Controls.OfType(Of TextBox)()
Where Not String.IsNullOrWhiteSpace(T.Text)
Select T Order By T.Name).FirstOrDefault
If Box IsNot Nothing Then
CType(Me.Owner, Form1).TextBox1.Text = Box.Text
End If
CType(Me.Owner, Form1).ActiveControl = CType(Me.Owner, Form1).cmdClose
Close()
End Sub
End Class
Image:
edit: now i only need to make the checkbox into locked textboxes, one line from the text file each.

Related

Try to read text , put on list , then compare on list and finally replace txt file

Trying to read a .txt file , put items to list, then on textbox change compare if the string exists in the list. Finally write the new list on the same .txt file.
Public Class Form1
Dim stockList As New List(Of String)
private sub
ListBox1.Items.AddRange(IO.File.ReadAllLines("C:\Users\path\file.txt"))
end sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles
TextBox1.ReadOnlyChanged
Dim text As String = TextBox1.Text
If TextBox1.Text <> "TRAINING" Then
For Each item As Object In ListBox1.Items
If item.ToString = text Then
MsgBox("This code has already been used.", 0, "cheat attempt violation") ' Else alert the user that item already exist
Else
ListBox1.Items.Add(TextBox1.Text)
End If
Next
End If
IO.File.WriteAllLines("C:\Users\path\file.txt", ListBox1.Items.Cast(Of String).ToArray)
End Sub
Instead of using a UI control to store data, you should store the data in a variable. I'm not sure if you really need to show the data in a ListBox, so in the following example code I didn't.
If you use a List(Of String) instead of an array of strings, it is simpler to add another item before saving it.
The Contains method I used in the example can take a second parameter which does the comparison of the item - I guessed that you might want to ignore the case (e.g. "ABC" is the same as "aBc") so I used StringComparer.CurrentCultureIgnoreCase.
I suspect that you want to use the Control.Validating Event instead of the TextChanged event. When the data has been validated, the Control.Validated event handler is used to save it.
I put one TextBox and one Button on the form, so that the focus could change away from the TextBox, e.g. when pressing tab, to fire the validating event.
Imports System.IO
Public Class Form1
Dim dataFile As String = "C:\temp\grains.txt"
Dim alreadyUsed As List(Of String) = Nothing
Sub LoadAlreadyUsed(filename As String)
'TODO: Add exception checking, e.g., the file might not exist.
alreadyUsed = File.ReadAllLines(filename).ToList()
End Sub
Sub SaveAlreadyUsed(filename As String)
File.WriteAllLines(dataFile, alreadyUsed)
End Sub
Function CodeIsAlreadyUsed(newCode As String) As Boolean
Return alreadyUsed.Contains(newCode, StringComparer.CurrentCultureIgnoreCase)
End Function
Private Sub TextBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
' Do nothing if the user has clicked the form close button
' See https://stackoverflow.com/questions/15920770/closing-the-c-sharp-windows-form-by-avoiding-textbox-validation
If Me.ActiveControl.Equals(sender) Then
Exit Sub
End If
Dim txt = DirectCast(sender, TextBox).Text
If CodeIsAlreadyUsed(txt) Then
MessageBox.Show("This code has already been used.", "Cheat attempt violation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
e.Cancel = True
End If
End Sub
Private Sub TextBox1_Validated(sender As Object, e As EventArgs) Handles TextBox1.Validated
' The Validated event is raised before the FormClosing event.
' We do not want to save the data when the form is closing.
If Me.ActiveControl.Equals(sender) Then
Exit Sub
End If
Dim txt = DirectCast(sender, TextBox).Text
alreadyUsed.Add(txt)
SaveAlreadyUsed(dataFile)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadAlreadyUsed(dataFile)
End Sub
End Class

Selecting items in a listbox with drawmode set to ownerdrawfixed

I have a listbox which I wanted some items to be a different color, and I understand to do this I have to set the drawmode to ownerdrawfixed. This works fine, but, now I can't retrieve a selected item. With the drawmode set to normal, when I click on an item in the listbox, I have it put that text into a textbox. With the drawmode set to ownerdrawfixed, when I click on an item, I get an error that "conversion from type 'item' to type 'string' is not valid. Also, the listbox is no longer sorted, even tho the sorted property is set to true (when in ownerdrawfixed mode).
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim ac As Integer
LstAll.DrawMode = DrawMode.OwnerDrawFixed
MaxRec = 708
ChkShow = True
FileOpen(1, "C:\MyMov3\MovData.mdt", OpenMode.Random, , , Len(Mv3Rec))
For x = 1 To MaxRec
FileGet(1, Mv3Rec, x + 1)
'This If loop for the colored text
If Mv3Rec.Rc3Mlti = True And ChkShwMlti.Checked = True Then
ac = Asc(Trim(Mv3Rec.Rc3MTitle))
If ac > 0 Then
Dim i As New Item()
i.ItmColor = Color.Red
i.Txt = Trim(Mv3Rec.Rc3MTitle)
LstAll.Items.Add(i)
End If
End If
If ChkShow = True Then
Dim i As New Item() 'Needed for the black text when in ownerdrawfixed mode
i.ItmColor = Color.Black 'Needed for the black text when in ownerdrawfixed mode
i.Txt = Trim(Mv3Rec.Rc3Title) 'Needed for the black text when in ownerdrawfixed mode
LstAll.Items.Add(i) 'Needed for the black text when in ownerdrawfixed mode
'LstAll.Items.Add(Trim(Mv3Rec.Rc3Title)) 'This line adds the text when in normal mode
End If
Next
FileClose(1)
End Sub
Private Sub LstAll_DrawItem(sender As Object, e As System.Windows.Forms.DrawItemEventArgs) Handles LstAll.DrawItem
If e.Index < 0 Then Return
Dim i As Item
i = TryCast(LstAll.Items(e.Index), Item)
If i IsNot Nothing Then
e.Graphics.DrawString(i.Txt, e.Font, New SolidBrush(i.ItmColor), e.Bounds)
End If
End Sub
Private Sub LstAll_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles LstAll.SelectedIndexChanged
TextBox1.Text = LstAll.SelectedItem
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
End
End Sub
End Class
Public Class Item
Public Txt As String
Public ItmColor As Color
End Class
This code is only the essential parts.... and was tested in a new project on a blank form. With a Listbox (renamed to LstAll) A textbox, a checkbox (renamed to ChkShwMlti). This gives the same error as in the program that I need it to work in. It does however use a file that I did not include the Structure for... but I think you can get the idea.
I have figured out this problem. In the LstAll.SelectedIndexChanged
Private Sub LstAll_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles LstAll.SelectedIndexChanged
Dim i As New Item
i = LstAll.SelectedItem
TextBox1.Text = i.Txt
End Sub
this worked as needed.

VB.NET how to populate a ComboBox in an UserControl from a Form

I have an UserControl where data from MySQL table loads in a ComboBox while it is loading.
Private Sub LoadFeeGroup()
Try
OpenConnection()
qry = "SELECT GroupId, GroupName FROM master_fee_group WHERE Stat='1' ORDER BY GroupName ASC"
Dim da As New MySqlDataAdapter(qry, conn)
Dim ds As New DataSet
da.Fill(ds, "master_fee_group")
With CmbGroup
.DataSource = ds.Tables("master_fee_group")
.DisplayMember = "GroupName"
.ValueMember = "GroupId"
End With
If CmbGroup.Items.Count > 0 Then
CmbGroup.SelectedIndex = 0
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
CloseConnection()
End Try
End Sub
And this Subroutine is being called when the UserControl is being loaded.
Private Sub AdmissionFeeUc_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadFeeGroup()
End Sub
Now user can add any Fee Group Name (if not added previously) by opening a form.
Now I want to call this LoadFeeGroup() subroutine from that form so that user can see the added Fee Group Name in the ComboBox of the UserControl after closing the form.
Something like...
Private Sub FormFeeGroup_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
' Code for calling the UserControl subroutine..
End Sub
I have tried to call the Subroutine like below,
but failed.
How can I do that ?
UPDATE
I have added a button in the UserControl.
Private Sub BtnNewGroup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnNewGroup.Click
Dim frmFeeGroup As New FormFeeGroup
Dim dlgres As DialogResult = frmFeeGroup.ShowDialog()
If DlgRes <> DialogResult.OK Then
Return
Else
LoadFeeGroup()
End If
End Sub
And in the FormClosing event
Private Sub FormFeeGroup_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If Me.DialogResult <> Windows.Forms.DialogResult.OK Then
Return
Else
'nothing to do
End If
End Sub
And in the Close button in the form,
Private Sub BtnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnClose.Click
Me.DialogResult = Windows.Forms.DialogResult.OK
Me.Close()
End Sub
My purpose is Partially served. Partially because, If I open the Form from the menu, the ComboBox is not updated.
You could create your own constructor for the form where you must pass a user control instance to it. That way you cannot create an instance of the form without specifying which user control it should be "tied" to.
For instance, put this in your form's code:
Public Property TargetFeeUc As AdmissionFeeUc
Public Sub New(ByVal FeeUc As AdmissionFeeUc)
InitializeComponent() 'Must be called before anything else.
Me.TargetFeeUc = FeeUc
End Sub
Then to create a new form instance you'll always be forced to give it an AdmissionFeeUc control.
'If written inside the user control's code:
Dim frmFeeGroup As New FormFeeGroup(Me)
'If written somewhere else:
Dim frmFeeGroup As New FormFeeGroup(<user control instance here>)
'...for example:
Dim frmFeeGroup As New FormFeeGroup(AdmissionFeeUc1)
And whenever you want to update the user control from your FormFeeGroup form you just need to call:
TargetFeeUc.LoadFeeGroup()
EDIT:
To get the user control instance if it was created dynamically you have to set the control's Name property when creating it, then you can reference it via:
<target control or form>.Controls("<user control name here>")
'For example:
Me.Controls("MyFeeUc")
'Or for sub-controls:
Me.Panel1.Controls("MyFeeUc")

Custom Textbox Zoom - Return text to active datagridview cell?

I have 2 Datagridview controls in same form. Each Datagrid has some columns where user will write long texts, so I designed form with RichTextBox that opens when user double-clicks these columns to enlarge text-entry. Code works, but I want to use same form for both Datagrids, so I should somehow return text to active datagridview cell. Here is my code (for Datagridview1):
TextZoomForm:
Public Class TextZoomForm
Public OpenedForm1 As New Form1
Private Sub RichTextBox1_DoubleClick(sender As Object, e As EventArgs) Handles RichTextBox1.DoubleClick
OpenedForm1.DataGridView1.CurrentCell.Value = RichTextBox1.Text
OpenedForm1.Label24.Focus()
Me.Close()
End Sub
Private Sub TextZoom_Load(sender As Object, e As EventArgs) Handles Me.Load
RichTextBox1.Text = OpenedForm1.DataGridView1.CurrentCell.Value
End Sub
End Class
DataGridView1_CellMouseDoubleClick in Form1:
Private Sub DataGridView1_CellMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDoubleClick
If e.ColumnIndex = 1 Then
Dim cp = Cursor.Position
cp.Y += CInt(Cursor.Size.Height * (-0.5))
cp.X += CInt(Cursor.Size.Width * 0.8)
Dim f As New TextZoomForm()
f.OpenedForm1 = Me
f.Show()
f.Location = New Point(cp)
End If
End Sub
Any ideas on how to return text to active datagridview cell?
Change your zoomed form so that it doesn't know where its data comes from. Instead the control using it will pass the data.
Public Class TextZoomForm
Public Property ZoomedText As String
Get
Return RichTextBox1.Text
End Get
Set(value As String)
RichTextBox1.Text = value
End Set
End Property
Private Sub RichTextBox1_DoubleClick(sender As Object, e As EventArgs) Handles RichTextBox1.DoubleClick
Me.Close()
End Sub
End Class
To call the form change your code to the following:
Private Sub DataGridView1_CellMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDoubleClick
...
Dim f As New TextZoomForm()
f.ZoomedText = DataGridView1.CurrentCell.Value
f.ShowDialog()
'Great breakpoint location.
DataGridView1.CurrentCell.Value = f.ZoomedText
Label24.Focus()
....
End Sub
Using ShowDialog prevents the user from changing the current cell part way through your call.
If you need it modeless then you should:
store the cell that the user has selected
handle the FormClosing event.
Test the DialogResult to make sure the user pressed ok
write the data back to the stored cell.

Access textboxes dynamically created at runtime

I add textboxes dynamically at runtime. How do I access them later in the program?
First name the dynamically created control
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim MyTextBox As New TextBox
MyTextBox.Name = "MyTextBox"
Me.Controls.Add(MyTextBox)
end sub
Somewhere else in the program:
'set text
Me.Controls("MyTextBox").Text = "Hi there"
'fetch text
Dim thetext = Me.Controls("MyTextBox").Text
'fetch textbox
Dim tb As TextBox = CType(Me.Controls("MyTextBox"), TextBox)
tb.Text = ""
tb.BackColor = Color.Red
Another way is to loop through the me.controlls-collection and find the control that way (maybe you have set .tag="mycontrol" on those or something else...