I want to show a hidden object on form 1 from form 2 - vb.net

So I have this PictureBox and Label on form1 which is hidden and I want to show it when you press a Button in form2.
Form1 code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Label3.Hide()
Me.PictureBox3.Hide()
Form2 Code:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
PictureBox3.Show()
But picturebox3 is not declared in form2 so how can I access it?

There are several ways. As others have stated in answers, the following would be one solution
Declare a public property that returns the PictureBox in Form1
Pass an instance of Form1 to Form2, so Form2 can access this instance of Form1 and use the property
Source could look like this, for example:
In Form1
public PictureBox ThePictureBox
{
get { return this.pictureBox1; }
}
In Form2
private Form1 form1Instance;
public Form2(Form1 form1)
{
InitializeComponent();
form1Instance = form1;
}
public void Button_Click(object sender, EventArgs e)
{
this.form1Instance.ThePictureBox.Visible = true;
}
Another way would be: If Form2 is opened by Form1, you could declare an event in Form2, have Form1 subscribe to it and thus notify Form1 that the picture box should be visible. That way you do not have to expose a member that should otherwise be private to Form1.
This could look like this:
In Form1
private void OpenForm2()
{
Form2 f2 = new Form2();
f2.ShowPictureBox += ShowPictureBox;
f2.Show();
}
private void ShowPictureBox(object sender, EventArgs e)
{
this.pictureBox.Visible = true;
}
In Form2
public event EventHandler<EventArgs> ShowPictureBox;
protected void OnShowPictureBox()
{
if (ShowPictureBox != null)
ShowPictureBox(this, EventArgs.Empty);
}
private void Button_Click(object sender, EventArgs e)
{
OnShowPictureBox();
}
I'm aware of the fact that your example code is Visual Basic, but as you tagged the question "C#" I guess you should be able to translate this to VB.NET easily - my VB.NET is not fluent enough :-)

First of all, you need to be able to access your elements from the other forms (as you should make access modifiers internal or public).
Then you can call the related elements from another form by creating instance or passing the form to a method in other form. You should check this link for detailed explanation by the way.

In some situations, we need to use a control in more than one forms. This can be achieved by sharing the control between different forms
In your case, add the control in Form2 during button click, it should work.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Controls.Add(Form1.PictureBox)
End Sub
Note: Form1.PictureBox is a shared property. We should define it like this in Form1.vb
public Shared Property PictureBox As PictureBox
Get
Return Me.PictureBox3
End Get
End Property

Related

How to make a user select an image and save the image as a variable?

I am trying to create a VB.net form where the user can click on a button and it is associated with a specific image and when the user clicks the image and then clicks select it will add it to a variable.
If you need more information please let me know (this is the image of my form)
I wanted to know:
how to assign an image to a button ( so when you click it, it means that the user wants that image) I am not sure if my method is correct
how to assign the image that was selected to a variable (so that once the variable is called it will output the image)
and how to end the form once the image is selected. (once use clicks the select button it should end the form, or if the user clicks cancel it should end the form).
Public Class Form1
Private Property SelectedPictureBox() As Image
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Controls.OfType(Of ButtonPictureBox).ToList().ForEach(
Sub(box)
AddHandler box.Click, AddressOf AllButton_Click
End Sub)
End Sub
Private Sub AllButton_Click(sender As Object, e As EventArgs)
SelectedPictureBox = CType(sender, ButtonPictureBox).PictureBox
End Sub
Private Sub GetBtnSelect_Click(sender As Object, e As EventArgs) Handles GetBtnSelect.Click
If SelectedPictureBox IsNot Nothing Then
MessageBox.Show(SelectedPictureBox.Name)
Else
MessageBox.Show("Please select an image")
End If
End Sub
Private Sub BtnTropicalFloral_Click(sender As Object, e As EventArgs) Handles BtnTropicalFloral.Click
SelectedPictureBox = PictureBoxTropicalFloral.Image
End Sub
Private Sub BtnLightGeode_Click(sender As Object, e As EventArgs) Handles BtnLightGeode.Click
SelectedPictureBox = PictureBoxLightGeode.Image
End Sub
Private Sub BtnStripes_Click(sender As Object, e As EventArgs) Handles BtnStripes.Click
SelectedPictureBox = PictureBoxStripes.Image
End Sub
Private Sub BtnAuroraBorealis_Click(sender As Object, e As EventArgs) Handles BtnAuroraBorealis.Click
SelectedPictureBox = PictureBoxAuroraBorealis.Image
End Sub
Private Sub BtnDiagonals_Click(sender As Object, e As EventArgs) Handles BtnDiagonals.Click
SelectedPictureBox = PictureBoxDiagonals.Image
End Sub
Private Sub BtnComb_Click(sender As Object, e As EventArgs) Handles BtnComb.Click
SelectedPictureBox = PictureBoxComb.Image
End Sub
Private Sub BtnMountain_Click(sender As Object, e As EventArgs) Handles BtnMountain.Click
SelectedPictureBox = PictureBoxMountain.Image
End Sub
Private Sub BtnLandscape_Click(sender As Object, e As EventArgs) Handles BtnLandscape.Click
SelectedPictureBox = PictureBoxLandscape.Image
End Sub
Private Sub BtnGradient_Click(sender As Object, e As EventArgs) Handles BtnGradient.Click
SelectedPictureBox = PictureBoxGradient.Image
End Sub
Private Sub BtnAbstract_Click(sender As Object, e As EventArgs) Handles BtnAbstract.Click
SelectedPictureBox = PictureBoxAbstract.Image
End Sub
Private Sub BtnGeode_Click(sender As Object, e As EventArgs) Handles BtnGeode.Click
SelectedPictureBox = PictureBoxGeode.Image
End Sub
End Class
My VB is a bit rusty, so I'll have to give the answer in C#. I'm sure you'll get the gist, and will be able to translate it into VB.
First of all: whenever you see that you are repeating things, for instance by copy-paste, you should stop, and rethink your design: maybe it would be better to create a method for this, or an object.
All your PictureBox/Button combinations have some common behavior. This means that you should think of creating a class for it.
In your case, you have the combination of a Button and a PictureBox. You want to be able to set and get an Image. The PictureBox will show this image. Finally you want to be notified if the operator clicks the Button.
In the event handler of this Notification you want to know which pictureBox/Button combination sent the event. You get the image from this combination and close the form.
In WinForms, whenever you want to have a class that is a combination of several controls, you make a UserControl.
In Visual Studio, in the solution control, right click on the project (not the solution!) and select: Add new Item. Select to add a new User Control. Think of a proper name, I'll call this ImageSelectionControl
Use the visual studio designer to give ImageSelectionControl the proper size. Add a PictureBox and a Button. Also use the visual studio designer to add an EventHandler for if the operator clicks the button.
In the code of the User Control add the property to Set / Get an Image. The Image that you set will be displayed in the PictureBox; the Image that you get is the image that is displayed in the PictureBox.
Here comes the first chunk of C#:
public Image Image
{
get => this.pictureBox1.Image;
set => this.pictureBox1.Image = value;
}
I think in VB this will be very similar.
Now you want that users of your control (= software, not humanoids) get notified that the operator selects an image. Officially, you even want to hide how the operator selected this image: all you want to say: "Hey, the operator selected my image!"
Normally you would do this using an event:
The 2nd piece of C#:
public event EventHandler ImageSelected;
The event won't have any data. It will only say: "Hey, the operator selected my image!". The event event handler will have to find out which user control raised the event, and fetch the image.
Ok, raise the event:
private void OnImageSelected()
{
this.ImageSelected?.Invoke(this, EventArgs.Empty);
}
It will be a bit more difficult to translate this into VB. What it does, it checks if there is at least one person who wants my events. If so it raises the event. with two parameters: the sender (which is me), and no parameters. Later we will see how the receiver of the event works.
Finally: if the operator clicks the button, he indicates that he wants to select the image in the user control, and thus OnImageSelected needs to be called
private void ButtonSelect_Clicked(object sender, EventArgs e)
{
this.OnImageSelected();
}
We've finished creating the UserControl. After Compilation you will find it in visual studio designer toolbox.
So we'll go to the form that will have to display the eleven PictureBox-Button combinations. Let's call this form: ImageSelectionForm.
Using Visual Studio Designer, add 11 ImageSelectionControls. If you know already at design time which control will show which image, you can do this in the designer, similarly to how you set the text or the background of a button.
If you only know at run-time which control should show which image, consider to add a method, for instance if you want to load it from file:
void ShowImage(ImageSelectionControl imageSelectionControl, string imageFileName)
{
Image image = this.LoadImageFromFile(imageFileName);
this.imageSelectionControl.Image = image;
}
Or maybe you have a different method to decide which ImageSelectionControl should displaye which image. I guess you get the gist.
Almost done. ImageSelectionForm needs to be notified about the selected image, so just like you would do with a button, you need to subscribe to event ImageSelected.
In the constructor or ImageSelectionForm, subscribe to the events:
private ImageSelectionForm()
{
InitializeComponent();
// subscribe to events
this.controlBlueGeod.ImageSelected += this.ImageSelected;
this.controlAbstract.ImageSelected += this.ImageSelected;
...
}
Of course, you can put all ImageSelectionControls in one list and use foreach to subscribe (that is too much VB for me, no idea how to do this)
The event handler:
void ImageSelected(object sender, EventArgs e)
{
// we know that the sender is the one that holds the selected images:
ImageSelectionControl imageSelectionControl = (ImageSelectionControl)sender;
We will be closiing the form very soon, so we will have to remember this selected image somewhere in a property:
public Image SelectedImage {get; set;}
So continuing the event handler:
this.SelectedImage = imageSelectionControl.Image;
this.DialogResult = DialogResult.OK;
this.Close();
}
So the selected image is saved. The dialog result is set to indicate that an image was selected, not cancel clicked. And the form is closed.
Showing the form and process the selected image
The form that has to show ImageSelectionForm has a procedure:
private void ShowImageSelectionForm()
{
using (ImageSelectionForm dialog = new ImageSelectionForm())
{
// show the dialog and process the result:
DialogResult dlgResult = dialog.ShowDialog(this);
if (dlgResult == DialogResult.OK)
{
this.ProcessSelectedImage(dialog.SelectedImage);
}
else
{
// TODO: process cancel
}
}
}
There is one memory leak: if you created a lot of images, all images need to be Disposed after usage. Best is to by overriding Component.Dispos(bool)
ImageSelectionControl:
protected override Dispose (bool disposing)
{
if (disposing && this.Image != null)
{
this.Image.Dispose();
}
}
ImageSelectionForm:
protected override Dispose (bool disposing)
{
if (disposing)
{
this.controlBlueGeod.Dispose();
this.controlAbstract.Dispose();
...
} ​
​}
This is quite a nuisance for 11 controls. Therefore quite often a Form or a UserControl has a System.ComponentModel.IContainer components. If you add your ImageSelectionControls to this container, then the ImageSelectionControls will be automatically disposed when ImageSelectionForm is disposed.
​
You have two Controls that work together to allow users to preview and select one or more Images in the UI. When you have this kind of scenario, build a UserControl that contains all the required UI elements and the logic used perform this action.
To build this UserControl:
Open the Project menu and select Add User Control...
Right away, set (in this order):
AutoScaleMode = Dpi
Font = Segoe UI, 9pt
BackColor = Color.Transparent
Set a Size that you think is the minimum required to show an Image and a Button
When you have found the right size, set also the MinimumSize to this value
Add a Button to the UC, configure it as needed, set its Width as the Width of the UC minus 4 pixels. Position the Button at the bottom of UC, 2 pixels to the left and set Anchor = Bottom, Left, Right
Add a PictureBox, same Width and Left location as the Button. Set the Height as required, then Anchor = Top, Bottom, Left, Right
Design completed. Build the Project.
Now, your UserControl needs to provide means to set an Image to the PictureBox and the Text of the Button.
You can add two Public Properties of Type Image and String that, when a value is assigned, set the PicureBox.Image property and the Button.Text property.
Also, when the Button is clicked, the UserControl needs to notify that the User has performed a selection, so whatever other code needs to do something with this information, will be able to act on it.
In an event-driven UI, you make your UC raise a public event that interested parties can subscribed to, to receive a notification that something happened.
You just need to define a Field of Type Event and give it a name. In this case, e.g.:
Public Event ImageSelection As EventHandler
When the Button is clicked, you raise the event:
RaiseEvent ImageSelection(Me, EventArgs.Empty)
The sample UserControl is named ImagePicker, the PictureBox is named picImage and the Button is btnSelectImage
Public Class ImagePicker
Public Event ImageSelection As EventHandler
Private m_Picture As Image = Nothing
Private m_Title As String
Public Property Picture As Image
Get
Return m_Picture
End Get
Set
m_Picture = Value
picImage.Image = m_Picture
End Set
End Property
Public Property Title As String
Get
Return m_Title
End Get
Set
m_Title = Value
btnSelectImage.Text = m_Title
End Set
End Property
Private Sub btnSelectImage_Click(sender As Object, e As EventArgs) Handles btnSelectImage.Click
RaiseEvent ImageSelection(Me, EventArgs.Empty)
End Sub
End Sub
In your Form (for example), you can the subscribe to this event to receive a notification that the User has selected the Image of one of your UserControls.
When the event is raised, the sender object is the UserControl that raised the event. You can then cast sender to your UserControl Type and read the Public Property that references the Image you have assigned to it.
In a Form, you can add some of your UserControls to a FlowLayoutPanel (in the example, named flpPreviews), which will take care of the layout of these Controls.
While adding the UserControls, you set their Public Properties and also subscribe to the Public event.
When the event is raised, cast sender to ImagePicker and read its public Picture property to get the reference of the Image selected:
Public Class SomeForm
Public Sub New()
InitializeComponent()
' Add three ImagePicker UserControls to a FlowLayoutPanel
For i As Integer = 0 To 2
Dim picker = New ImagePicker()
picker.Picture = [Some Image]
picker.Title = "Some Title"
' Subscribe to the event
AddHandler picker.ImageSelection, AddressOf ImageSelectionChanged
flpPreviews.Controls.Add(picker)
Next
End Sub
Private Property SelectedImage As Image
Private Sub ImageSelectionChanged(sender As Object, e As EventArgs)
SelectedImage = DirectCast(sender, ImagePicker).Picture
' Show the selected Image in a PictureBox, child of the Form
picSelected.Image = SelectedImage
End Sub
End Class

VB Adding an item to listbox on a different form giving null reference exception

I am getting a an Null reference exception when trying to add an item to a listbox in a different form.
This is my error at run time.
An unhandled exception of type 'System.NullReferenceException'
occurred in ... Additional information: Object reference not set to an
instance of an object.
I am trying to connect the Mainform by initializing it at the top of the class of the secondForm. after I have my data i want to add it to a listbox it the mainform.
Public Class FormHairdresser //The second form
Dim varMainForm As FormMain //connecting the forms ?
Private Sub btnAddHairdresser_Click(sender As Object, e As EventArgs) Handles btnAddHairdresser.Click
hairdresser = HairdresserChoices(HairdresserID) // get the data
varMainForm.lstListBox.Items.Add(hairdresser) //Run time error breaks here.
All i had to to was write the form name instead of ininalised variable.
FormMain.lstListbox.Items.Add("item")
Instead of
Dim varMainForm As FormMain
varMainForm.ListBox.Items.Add("item")
You cannot simply create a new instance of your main form (as has been suggested and expect that to work, you need an actual reference to the mainform that you have created. To help you see the logic involved;
Create a new Winforms project. In the default Form1 add a textbox and a button.
Now add a new form to this application (you can leave it with its default name of Form2. To this form add a TextBox (call it myTextBox) and a button.
Now go back to your first form and doubleclick the button to access the click handler in code. Add the following:
Dim frm as New Form2
frm.Show
Press f5 and click the button and you'll see a new form 2. So far so good.
Now open up the code for Form2 and add the following code so that it ends up looking like this:
Public Class Form2
Private frm As Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
frm.TextBox1.Text = myTextBox.text
End Sub
End Class
build, press f5 and click the button on form1, in the new form2 enter some text in the text box and click the button, you get your null reference exception. The reason you get this is because at the moment the private field frm inForm2 refers to Nothing.
Now open up the code in Form2 and add a constructor and the following code so that it ends up looking like this:
Public Class Form2
Private frm As Form1
Public Sub New(byval frm1 As Form1)
'first we should make sure that we have a parameter to play with
If Not IsNothing(frm1) Then
frm = DirectCast(frm1,Form1)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
frm.TextBox1.Text = myTextBox.text
End Sub
End Class
Finally go back to your first forms buttonclick handler and change the code slightly so that it looks like this;
Dim frm as New Form2(Me)
frm.Show
Build and run your application, now when you enter text into the textbox in form2 and click the button it will appear in the textbox in Form1.
The reason why this happens is because you have passed an actual reference to the form1 that was originally created when the application started to form2. By casting that reference to your private field used to represent form1 in form2 you can then use it to properly refer to things on form1. This is a very simple concept but one which you need to learn before you will make progress programming.
the Problem is with your initialization of the formmain.with out proper initialization the object you are creating is nothing other than Null.To avoid this we use New Operator.The New operator can often be used to create the instance when you declare it.
So the initialization will look like
Dim varMainForm As New FormMain
Hope this Helps.For more Reference Object Initialization Errors
update:
Dim varMainForm As FormMain //connecting the forms ?
Private Sub btnAddHairdresser_Click(sender As Object, e As EventArgs) Handles btnAddHairdresser.Click
hairdresser = HairdresserChoices(HairdresserID) // get the data
varMainForm = New FormMain
varMainForm.lstListBox.Items.Add(hairdresser) //Run time error breaks here.
Try This.
Public Class FormHairdresser //The second form
Private Sub btnAddHairdresser_Click(sender As Object, e As EventArgs) Handles btnAddHairdresser.Click
Dim varMainForm As FormMain
hairdresser = HairdresserChoices(HairdresserID)
varMainForm.lstListBox.Items.Add(hairdresser)

Passing event to the parent form

I have a little problem here. I'm trying to transfer/pass/raise the events of an owned form to his parent. Lets look at my example:
Lets say i have a form that initialize a CustomPanel (simply a class that inherits from System.Windows.Forms.Panel). It also have an event handler (it could be an other event, not necessarily a click event):
Public Sub New()
Me.Size = New Size(1000,1000)
Dim pnl1 As New CustomPanel()
pnl1.Location = New Point(0,0)
pnl1.size = New Size(100,100)
Me.Controls.Add(pnl1)
End Sub
Private Sub form1_Click(sender As Object, e As EventArgs) Handles Me.Click
MsgBox("I got it!")
End Sub
I did something similar and when I clicked on the CustomPanel (pnl1) the parent container (form1) did not receive a click event ... which is understandable. I tried to look in the properties of the CustomPanel (pnl1) if i could find something interesting like "click through" or "raise event to parent" (I was desperate here) but without success. I said alright, I will handle the events that I need to pass to parent in the CustomPanel class but I cant find a solution here neither:
Imports System.Windows.Forms
Public Class CustomPanel
Inherits Panel
Public Sub New()
End Sub
Private Sub CustomPanel_Click(sender As Object, e As EventArgs) Handles Me.Click
'What to put here?
'Me.Parent.?
End Sub
End Class
I just want to know if its possible to throw/raise/pass events to the parent. One thing is sure, its that i shouldn't have to and i cannot add anything else to the parent form. The reason is simple, i could have over 100 controls in this parent form and they could be added dynamically. And on top of that, these controls could also have their own controls inside! So i could have something like:
pnl99 call parent click -> pnl98 call parent click -> ... until the parent of the control really handle the click event ... -> form1 perform click event
Maybe its hard to understand but if you can help me I would appreciate.
Using a custom event, that the form owning the panel subscribes to. Raise Event
Public Sub New()
Me.Size = New Size(1000,1000)
Dim pnl1 As New CustomPanel()
pnl1.Location = New Point(0,0)
pnl1.size = New Size(100,100)
Addhandler pnl1.MyClickEvent, AddressOf pl_Click
Me.Controls.Add(pnl1)
End Sub
Private Sub pl_Click()
MsgBox("I got it!")
End Sub
Custom panel:
Public Class CustomPanel
Inherits Panel
Public Event MyClickEvent
Private Sub CustomPanel_Click(sender As Object, e As EventArgs) Handles Me.Click
RaiseEvent MyClickEvent()
End Sub
End Class
On the child form
Imports System.Windows.Forms
Imports STAS_PLC_Link_Lib
Public Class ChildForm
Public Event MyClick()
'.....rest of code
On the parent form
Public Class ParentForm
Private Sub GetSomeClick() Handles ChildFor.MyClick
System.Console.WriteLine("test")
End Sub
end Class

Multiple Listboxes, One Selection

I have 2 List Boxes on my form, but I only want to be able to make a single selection between both, how would I go about this?
I, of course, tried doing this first...
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
ListBox2.ClearSelected()
End Sub
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
ListBox1.ClearSelected()
End Sub
But since that causes the selected index to be changed it clears what you have just selected as well...
Thanks for any help!
You can test the reason why Selected index changed, something like that:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
// If listBox2 focused i.e. user clicked list box2 - do nothing:
// one should not try to clear list box2 selection
if (listBox2.Focused)
return;
listBox2.ClearSelected();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e) {
// If list box1 is in focus that means that user just have selected itme there;
// so, do nothing: we shouldn't erase user's selection
if (listBox1.Focused)
return;
listBox1.ClearSelected();
}
First, your question is tagged as C# but the code sample is in VB.
Second, I would do it in C# as follows:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox2.SelectedIndexChanged -= new System.EventHandler(this.listBox2_SelectedIndexChanged);
listBox2.ClearSelected();
listBox2.SelectedIndexChanged += new System.EventHandler(this.listBox2_SelectedIndexChanged);
}
And do the same with the other event handler.

Handling an event of control which is inside of usercontrol

Soon I asked for help to read properties of textbox which is inside usercontrol.
Accessing to control inside of usercontrol
As I have been suggested I make one very simple public class with name xTextBox and use it as textbox in my usercontrol. That work fine.
Public Class xTextBox
Inherits TextBox
End Class
Now I can simply read a property on that xTextbox from main program which contain that usercontrol:
Dim s As Integer = myUserControl.xTextBox1.SelectionStart
But now is a problem that I can't get events of that Textbox in main program.
Maybe I can declare 'Shadows Event TextChanged...' etc, but I will need more events in different situations where usercontrol would be, and intentionally raising every of them don't look elegant in mean of practical programming.
How to get events of those xTextbox to main program?
If the your new UserControl has only one control and Inherits TextBox, then you can just attach the events like normal, either with the Property Editor, or Manually with AddHandler. If things are more complicated than that I would probably create a panel and put your new TextBox's in it, then it will be a lot easier to access the events.
Public Class myUserControl
Inherits TextBox
End Class
Public Class Form1
Public Sub New()
InitializeComponent()
AddHandler MyUserControl1.TextChanged, AddressOf MyUserControl_textChanged
End Sub
Private Sub MyUserControl_textChanged(sender As Object, e As EventArgs)
Throw New NotImplementedException
End Sub
End Class
Or if your UserControl has Multiple Custom TextBox's in it, you can create a Custom Event and fire that in a common TextChanged Event on your UserControl and handle that in your Main Form.
Public Class UserControl1
Public Event TextChange(sender As Object, e As EventArgs)
Private Sub MyUserControl_TextChanged(sender As System.Object, e As System.EventArgs) Handles MyUserControl1.TextChanged, MyUserControl2.TextChanged
RaiseEvent TextChange(sender, e)
End Sub
End Class
Public Class Form1
Public Sub New()
InitializeComponent()
End Sub
Private Sub UserControl11_TextChange(sender As System.Object, e As System.EventArgs) Handles UserControl11.TextChange
MsgBox(CType(sender, TextBox).Name, MsgBoxStyle.Information)
End Sub
End Class