Labels & Text wont update accordingly - vb.net

I developed an application which is like a digital comprehension sheet activity.
The order of which this works is:
A user double clicks an underscored text area on a text box
A form opens which asks them to place an answer
The answer is validated, if true it goes back to the original form
The issue here is that for some odd reason my labels don't update on step 3, as- well as the text. I have a label named lbAnswerStatus which notifies the user if they have a correct answer, the text does not update, and the 'SelectedText' on Form 1 should be replaced with the answer (if correct)
Here is my code:
Form 1 (when textbox is clicked):
Form2.Answer(answers(counter))
answers(counter) represents the correct answer being passed on, to compare with users answer in form 2
Form 2:
If tbAnswer.Text = theanswer Then
Form1.answerStatus(True, theanswer)
Form 1:
Public Sub answerStatus(status, answer)
If status = true Then
Form2.Close()
rtb.SelectedText = answer
lbAnswerStatus.ForeColor = Color.Green
End If
End Sub
My first assumption was that the Rich text box's SelectedText wasn't changing because it didn't have focus on it however, the lbAnswerStatus color didn't change either, so I figured that there was issues with making modifications to the form.
I used a message box to test whether lbAnswerStatus.Text would pop up and it did, so it can read but not write.
I also attempted to change the text of the label and selectedtext of the textbox in step 1 and it worked fine.
Any ideas what may be causing this issue?
Thanks.

I guess that you want your Form2 (AnswerForm) presented as a modal dialog. Doing that, you can return a result. You didn't say what you want to happen to the answer status label or the answer form if the supplied answer is incorrect.
Just as an example of how it can be done, create a new Windows Forms project. On Form1, place a button (Button1) and a label ("lblAnswerStatus"). Add a new form named "AnswerForm" to the project, and add a TextBox ("TextBox1") and a button ("bnDone").
As code for AnswerForm:
Public Class AnswerForm
Private statusLabel As Label
Private answerText As String
Private Sub bnDone_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bnDone.Click
If TextBox1.Text.Equals(answerText, StringComparison.CurrentCultureIgnoreCase) Then
' Alternative 1: set the color here if you want to
statusLabel.ForeColor = Color.Green
' return a value indicating success
Me.DialogResult = Windows.Forms.DialogResult.Yes
Me.Close()
Else
' indicate error
statusLabel.ForeColor = Color.Red
End If
End Sub
Public Sub New(ByVal statusLabel As Label, ByVal answerText As String)
InitializeComponent()
Me.statusLabel = statusLabel
Me.answerText = answerText
End Sub
End Class
and as code for Form1:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
lblAnswerStatus.ForeColor = Color.Blue
Using answerFrm As New AnswerForm(lblAnswerStatus, "X")
Dim dlgResult = answerFrm.ShowDialog()
' Alternative 2: use this if you want to change the color in this handler
If dlgResult = DialogResult.Yes Then
lblAnswerStatus.ForeColor = Color.Purple
End If
End Using
End Sub
End Class
If you click Button1 on Form1, a dialog box appears. Type into its TextBox1 and click bnDone. Because the instance of AnswerForm has a reference to lblAnswerStatus (supplied in its constructor), it is easy to update the latter, e.g. it turns red if you enter the wrong answer.

Related

parse value from datagrid to button name

I'm building a form that has many buttons, all buttons do the same thing: add 1 every time they are clicked. Every pressed button is sent to a datagridview along with the time they are pressed. Datagrid values look like this:
a_1_serv (button name), 18:05:00(time).
Sometimes I want to delete the last row. Everything works fine so far.
When I delete the last row, I want to change the text of the button (a_1_serv).
I can parse the dgv value (a_1_serv) to a variable but I can't bind it to the appropriate button name so I can control it.
Is there a way to do it?
Don't store your program state in your UI
Create a data structure to hold the information, and let the DataGridView be a "view", not treating it as a variable. You will save yourself headaches vs using the UI as a variable.
That said, create a class to represent your information
Public Class Data
Public Sub New(button As Button, time As DateTime)
Me.Button = button
Me.Time = time
End Sub
<System.ComponentModel.Browsable(False)>
Public Property Button As Button
Public ReadOnly Property Text As String
Get
Return Button.Name
End Get
End Property
Public Property Time As DateTime
End Class
And your code can manipulate the data in a variable off the UI. Bind the data to the DataGridView for display.
Private datas As New List(Of Data)()
Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click
addButton(DirectCast(sender, Button))
End Sub
Private Sub RemoveLastButton_Click(sender As Object, e As EventArgs) Handles RemoveLastButton.Click
removeLast()
End Sub
Private Sub addButton(b As Button)
datas.Add(New Data(b, DateTime.Now))
bindData()
End Sub
Private Sub removeLast()
Dim b = datas.Last.Button
b.Text = "new text" ' change to whatever
datas.RemoveAt(datas.Count - 1)
bindData()
End Sub
Private Sub bindData()
DataGridView1.DataSource = Nothing
DataGridView1.DataSource = datas
End Sub
This does exactly what you stated but there may be inconsistency in these two bits of information you provided: a_1_serv (button name) and I want to change the text of the button .... This changes the button text but not the name. The name is displayed in the grid. You can change the data class to display the text or whatever. But the point is this approach will keep your data off the UI and you won't need to look up the control by name anymore.

Combobox custom control with a lid

I have created a custom combobox with a label to cover the combobox (as it's very ugly) when it's not in use. The label, witch is the lid should show the display member. The covering and uncovering forks fine however the text on the label displayed is the previous value and not the current one. Passing over the label with the mouse, triggers the labels mouse enter event and than the display value is correct.
Here is the code for the custom control.
Public Class ComboBoxWithALid
Inherits ComboBox
Private WithEvents Lid As New Label With {.BackColor = Color.LightCyan, .ForeColor = Color.Black,
.TextAlign = ContentAlignment.MiddleCenter}
Protected Overrides Sub OnDataSourceChanged(ByVal e As EventArgs)
MyBase.OnDataSourceChanged(e)
Lid.Location = Location
Lid.Size = Size
Parent.Controls.Add(Lid)
Lid.BringToFront()
End Sub
Private Sub Lid_MouseEnter(sender As Object, e As EventArgs) Handles Lid.MouseEnter
Lid.SendToBack()
End Sub
Protected Overrides Sub OnMouseLeave(e As EventArgs)
MyBase.OnMouseLeave(e)se
Lid.Text = SelectedText
Lid.BringToFront()
End Sub
Protected Overrides Sub OnDropDownClosed(e As EventArgs)
MyBase.OnDropDownClosed(e)
Lid.BringToFront()
Lid.Text = SelectedText
End Sub
End Class
To test the control, drag the control from the tool box to your form and bind the control to any table you have
I tried to use text in place of selected text - same results
I found the solution. Change the move statement to:
Lid.Text = Items(SelectedIndex)(DisplayMember)
and is works.
SelectedText is for the highlighted portion of the text that is currently selected, not the selected item. You probably want something like this:
If SelectedIndex = -1 Then
Lid.Text = String.Empty
Else
Lid.Text = Items(SelectedIndex).ToString()
End If
Yes, you have an annoying control.

How do I use the Tag property with forms and code in VB 2012?

I am writing a program using a database for customers and technicians. The main form (CustomerIncidents) has a toolstripbutton that opens a different form to (SearchByState) where the user inputs a state code and looks for any incidents.
If the user clicks into one of the datagrid cells I want that customers information to be stored in the TAG so that when the form is closed using the OK button that it will show back up in the main form (CustomerIncidents).
Edited 03/11/14 12:21pm
The problem is in the Main Form. When I click the OK button in the Second Form it tries to convert the DialogResult Button to a String. I can't figure out how to fix it.
Customer Form (Main Form) Opens to Secondary Form
Private Sub btnOpenState_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnOpenState.Click
Dim frmSearchState As New FindCustomer
----->>Dim selectedButton As DialogResult = frmSearchState.ShowDialog()
If selectedButton = Windows.Forms.DialogResult.OK Then
CustomerIDToolStripTextBox.Text = frmSearchState.Tag.ToString
End If'
Search By State Form (Secondary Form) Or "Child Form"
Private Sub btnOk_Click(message As String, ByVal e As DataGridViewCellEventArgs) Handles btnOk.Click
message = CustomersDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString
Me.Tag = message
Me.DialogResult = DialogResult.OK
End Sub
The click event for a button does not have a DataGridViewCellEventArgs parameter, and will throw an exception when you try to use it.
You don't need to use the Tag property since you can just create your own property.
In your child form, create a property called GridValue:
Private Sub btnOk_Click(sender As Object, e As EventArgs) Handles btnOk.Click
If dgv.CurrentCell Is Nothing OrElse dgv.CurrentCell.Value Is Nothing Then
MessageBox.Show("A cell needs to be selected.")
Else
Me.DialogResult = DialogResult.OK
End If
End Sub
Public ReadOnly Property GridValue As String
Get
Return dgv.CurrentCell.Value.ToString
End Get
End Property
In your parent form, you can now access your information:
Using frmSearchState As New FindCustomer
If frmSearchState.ShowDialog(Me) = DialogResult.Ok Then
CustomerIDToolStripTextBox.Text = frmSearchState.GridValue
End If
End Using
My personal approach for doing this kind of stuff is to create a public property in the child form, having the same type as the DATA you want to take back to your main form. So instead of storing DataGridView's reference in Tag property, you should really be storing the actual value that was there in the cell that the user clicked on.
For example, if your DGV cell has a string value in it, you could do something like:
Public Readonly Property StateName As String
Get
If YourDGV.SelectedCell IsNot Nothing Then
Return YourDGV.SelectedCell.Value
Else
Return ""
End If
End Get
End Property
(I have written that code by hand, so there may be some syntax problems, but you should be able to get the idea.)
You can now use ShowDialog() in the main form to bring up this child form and upon OK or Cancel, you could check the value of StateName property of your child form to get this value. The thing to remember here is that closing a form doesn't dispose off all its constituent controls and properties and therefore you can access them even after the form has finished ShowDialog() call.

Edit Update DatagridView VB.Net (No Database)

Good day everyone.
I need your help in this project I am into (a Visual Basic program with no database.) It just contains a Datagridview, a Textbox, and three buttons (an "Add" Button, a "Edit" and an "Update" Button).
1 . Is there any way (like using "for loop") to automatically assign DataGridView1.Item("item location") to the one edited and be updated?
2 . Or is it possible to just click an item in the Datagridview then it will be edited at that without passing it to a Textbox, and to be updated at that.
The DataGridViewCellEventArgs variable (e in the method stub the designer will generate for you) of the double click event of the cell has RowIndex and ColumnIndex properties which refer to the position of the cell you clicked.
Save those (in a class variable possibly or a local one if that's all you need) and then refer to them when you update the cell in your DataGridView, possibly like this MyDataGridView.Item(e.ColumnIndex, e.RowIndex) or MyDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex) where e is the variable from the double click event handler.
For you cell double click event you could have something like this:
Private Sub DataGridView1_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
Using myEditor As New frmCellEditor(Me.DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value)
If myEditor.ShowDialog() = DialogResult.OK Then
Me.DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value = myEditor.NewCellValue
End If
End Using
End Sub
This will call a new instance of your editor and get a value from you. For the purpose of this demo I have made a form like this:
Public Class frmCellEditor
Public NewCellValue As Integer
Public Sub New(ByVal CurrentCellValue As Object)
InitializeComponent()
Me.TextBox1.Text = CStr(CurrentCellValue)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.NewCellValue = CInt(Me.TextBox1.Text)
Me.DialogResult = DialogResult.OK
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Call Me.Close()
End Sub
End Class
Which just has two buttons (Button1 = OK, Button2 = Cancel). When you click OK, it just returns the value 1 which then gets set as the value of the cell.
This is a VERY simplistic example, but it should provide you the basics of what you are trying to do.
UPDATE:
I updated the code for the editor interface so it will include handling for passing the value back and forth from the form with your datagridview.
In your project, make a new form called frmCellEditor. This forms has to have two buttons and a textbox (Make sure that the programmatic names match!). Replace the code with the code listed above. You will have to add Imports System.Windows.Forms above the class as well.
Amend the event handler for the cell double click event of your datagrid to pass the cell value when frmCellEditor is constructed (the line going ... New frmCellEditor(...).
How many columns does your DataGridView has?
Based on how you populate your DataGridView, I'll assume only 1.
Declare this on top of your form
Dim i as Integer
On your btnUpdate_Click Event (Just combine your Edit and Update button into One)
SELECT CASE btnUpdate.Text
Case "Update"
With DataGridView1
'Check if there is a selected row
If .SelectedRows.Count = 0 Then
Msgbox "No Row Selected for Update"
Exit Sub
End If
i = .CurrentRow.Index 'Remember the Row Position
Textbox1.Text = .item(0 ,i).value 'Pass the Value to the textbox
.Enabled = False 'Disable DataGridView to prevent users from clicking other row while updating.
btnUpdate.Text = "Save"
End With
Case Else 'Save
DatagridView1.Item(0,i).Value = Textbox1.Text
btnUpdate.Text = "Update"
END SELECT
Thanks for those who contributed to finding answers for this thread. I have not used your solutions for now (maybe some other time). After some research, I've found an answer for problem 2 (more user friendly at that):
2 . Or is it possible to just click an item in the Datagridview then
it will be edited at that without passing it to a Textbox, and to be
updated at that.
Here's what i did:
in Private Sub Form1_Load, just add:
yourDataGridView.EditMode = DataGridViewEditMode.EditOnEnter
in Private Sub yourDataGridView_(whatever event here: DoubleCellClick, CellContentClick, etc.) add:
DataGridView1(e.ColumnIndex, e.RowIndex).[ReadOnly] = False
DataGridView1.BeginEdit(False)

VB.NET Form Hiding Issue

I have a custom form, B. B is created by A, which has a handle to B.VisibleChanged.
B only has an OK and Cancel button on it, and I want to do some logic when OK is hit.
B's OK button is dealt with like this:
Me.Result = Windows.Forms.DialogResult.OK
Me.Hide()
The code in A is properly hit and run, but it never hides B. When I check the values of the properties on B, it shows me Visible = False.
Does anyone have any suggestions as to the possible cause of this issue?
Edit
This form was shown using the Show() command, as I'm making a later call to have the form flash using FlashWindow().
Not exactly sure about your question.
why not use me.Close() instead of me.Hide?
Is it OK to have multiple instances of B at a time? If not, go for ShowDialog.
If you can rephrase the question, someone can probably resolve your problem.
I suppose you want to display a messagebox with an ok & cancel button. Instead of using a form use a mesagebox.
eg:
DialogResult dgResult = MessageBox.Show("Click Yes or No", "Test App", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (DialogResult.OK == dgResult)
{
//Do what you want.
}
else
{
//Do nothing.
}
If you are going to use a form, to do that & wanted to modify the parent's form, it would be advisable to use delegates to prevent form B from modifying form A's variables.
Else: (Not recommended)
Declare form B as a member variable of form A.
when required instantiate form B.
do B.ShowDialog();
internally in OK & cancel do this.dispose();
Again when you need form B just instantiate. re - instantiation will not be too much of an overhead if you dont call it very often.
But if you only need OK Cancel, use message box instead.
The show/hide approach works for me:
Public Class frmViewChild ' your form A
Private WithEvents _edit As frmEdit
'code
Private Sub editCell()
Dim PKVal As String
Dim PKVal2 As String
Dim fieldOrdinalPos As Integer
Dim isLastField As Boolean
If _edit Is Nothing Then
_edit = New frmEdit
_edit.MdiParent = Me.MdiParent
End If
'code
_edit.init(<params>)
If Not _edit.isNothing Then
_edit.Show()
_edit.WindowState = FormWindowState.Maximized
_edit.BringToFront()
End If
End Sub
'code
Private Sub _edit_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles _edit.VisibleChanged
If Not _edit.Visible Then
WindowState = FormWindowState.Maximized ' revert after closing edit form
End If
End Sub
Public Class frmEdit ' your form B
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
Dim ret As Integer
doOK(ret)
If ret > -1 Then ' no error
Me.Hide() ' close form, but didn't cancel
End If
End Sub
HTH