I'm trying to change the image of a picture box in form2 from an usercontrol that is placed in form1 when I change the value in a combobox. I want the image to stream from an image link like this one "https://i.imgur.com/xxxxxx.png". This is what I have done yet.
This is form1 with the usercontrol put in it.
private void combobox_TextChanged(object sender, EventArgs e)
{
string newText = combobox.Text;
Form2 crsF = new Form2();
if (check_Enabled.Checked)
{
switch (newText)
{
case "White":
crsF.UpdatePictureBox("https://i.imgur.com/HDuKdEh.png");
break;
case "Red":
crsF.UpdatePictureBox("https://i.imgur.com/HDuKdEh.png");
break;
}
}
}
This is form2 that I want to change the image of
public void UpdatePictureBox(string streamLink)
{
var request = WebRequest.Create(streamLink);
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
pictureBox1.Image = Bitmap.FromStream(stream);
this.Refresh();
}
}
I start form2 with this code.
Form2 csrF;
private void combobox_CheckedChanged(object sender, EventArgs e)
{
crsF = new Form2();
if (combobox.Checked)
{
crsF = new CrosshairForm();
crsF.Show();
}
else if (!combobox.Checked)
{
Form2 obj = (Form2)Application.OpenForms["Form2"];
obj.Close();
}
}
I've tried many different things and I like to solve things myself by I really have spent some time on this function and I just can't manage to get it right, all help is appreciated.
CodePudding user response:
Here is the solution!
Form 1
using System;
using System.Windows.Forms;
namespace WinFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string Link;
private void combobox_SelectedIndexChanged(object sender, EventArgs e)
{
string newText = combobox.Text;
switch (newText)
{
case "White":
Link = "https://i.pinimg.com/564x/fc/80/7c/fc807ccc8b44a604c276614ed29f5067.jpg";
break;
case "Red":
Link = "https://i.imgur.com/HDuKdEh.png";
break;
}
}
private void check_Enabled_CheckedChanged(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(Link))
{
Form2 crsF = new Form2();
if (check_Enabled.Checked)
{
crsF.UpdatePictureBox(Link);
crsF.Show();
}
else if (!check_Enabled.Checked)
{
Form2 obj = (Form2)Application.OpenForms["Form2"];
if (obj != null)
{
obj.Close();
}
}
}
}
}
}
Form 2
using System.Windows.Forms;
namespace WinFormsApp2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void UpdatePictureBox(string streamLink)
{
System.Net.WebRequest request = System.Net.WebRequest.Create(streamLink);
System.Net.WebResponse response = request.GetResponse();
System.IO.Stream stream = response.GetResponseStream();
pictureBox1.Image = System.Drawing.Bitmap.FromStream(stream);
Refresh();
}
}
}