I've created a new form, in which I have a toolbox. When I press a button in that form, it should relay that information that has been entered by the user(toolboxbox value) to the main form, in which it should say that piece of information in a label.
Since the method to create that username from the toolbox is private, I cannot access it from any other way. Making it public does not seem to make a difference, neither does get,set (from the way I've been trying to atleast).
Picture that may help explaining it:
Code (in which to create user):
namespace WindowsFormsApplication3
{
public partial class Newuserform : Form
{
public Newuserform()
{
InitializeComponent();
}
private void buttonCreateUser_Click(object sender, EventArgs e)
{
string uname = textboxUsername.ToString();
}
public void Unamecreate()
{
}
}
}
Form1 Code (To receive created user):
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
{
Aboutform form2 = new Aboutform();
form2.Show();
}
private void newLocalUserToolStripMenuItem_Click(object sender, EventArgs e)
{
Newuserform formnewuser = new Newuserform();
formnewuser.Show();
}
}
}
you have a lot of options.
One way is to create an event and handle it in the main form.
public partial class Newuserform : Form
{
//the public property
public event EventHandler<string> UnameChanged;
public Newuserform()
{
InitializeComponent();
}
private void buttonCreateUser_Click(object sender, EventArgs e)
{
if (UnameChanged != null)
UnameChanged(textboxUsername.ToString()); //fire the event
}
}
Now, to "handle" the event, do the following in your main form:
private void newLocalUserToolStripMenuItem_Click(object sender, EventArgs e)
{
Newuserform formnewuser = new Newuserform();
formnewuser.UnameChanged += Handler;
formnewuser.Show();
}
private void Handler (object sender, string Uname)
{
// do something wit the new Uname.
}
note: recreating the Newuserform will require to cleanup previous attached resources.
Related
I have a usercontrol which have timer
public partial class Cumle : UserControl
{
private bool cond=false;
//Some Code....
private void timer2_Tick(object sender, EventArgs e)
{
//Some Code....
if(//some condition...)
cond=true;
}
}
I am working on windows form.I want to display a message box which shows me that cond is true.I want to make this stuff without using timer on Form.
public partial class Form1 : Form
{
//What I must write here?
}
As mentioned, you should use Events. I would go like this:
public partial class Cumle : UserControl
{
public event EventHandler ConditionChangedToTrue;
protected virtual void OnConditionChangedToTrue(EventArgs e)
{
if (ConditionChangedToTrue != null)
ConditionChangedToTrue(this, e != null ? e : EventArgs.Empty);
}
private void timer2_Tick(object sender, EventArgs e)
{
//Some Code....
if (true) // add your condition
{
cond = true;
OnConditionChangedToTrue(null);
}
}
}
public partial class Form1 : Form
{
private Cumle cumle = new Cumle();
public Form1()
{
InitializeComponent();
cumle.ConditionChangedToTrue+= Cumle_ConditionChangedToTrue;
}
private void Cumle_ConditionChangedToTrue(object sender, EventArgs e)
{
// add your event handling code here
throw new NotImplementedException();
}
}
You need to add a public event to your UserControl, and subscribe to it from your main form.
Something like this should do it:
public partial class Cumle : UserControl
{
public event Action<bool> ConditionChanged = delegate {};
private bool cond=false;
//Some Code....
private void timer2_Tick(object sender, EventArgs e)
{
//Some Code....
if(//some condition...)
{
cond=true;
ConditionChanged(cond);
}
}
}
Then in your form:
public partial class Form1 : Form
{
void SubscribeToConditionChanged()
{
myUserControl.ConditionChanged += ShowDlg;
}
void ShowDlg(bool condition)
{
MessageBox.Show("....");
}
}
Here is my code.
private void PlaceOrder_Click(object sender, EventArgs e)
{
MenuBox.Items.Clear();
TotalBox.Items.Clear();
total.Clear();
ordertotal = 0;
}
I want to add what is in the menu box to a another list box on another form.
Update
(added by jp2code)
Form1 (Main):
namespace WindowsFormsApplication1 {
public partial class RESTAURANT : Form
{
double soup = 2.49;
double ordertotal;
public RESTAURANT()
{
InitializeComponent();
}
private void RESTAURANT_Load(object sender, EventArgs e)
{
}
private void Add_Click(object sender, EventArgs e)
{
MenuBox.Items.Add("Soup");
TotalBox.Items.Add(String.Format("{0:C}", soup));
ordertotal += soup;
total.Text = Convert.ToString(String.Format("{0:C}", ordertotal));
}
private void TotalBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void PlaceOrder_Click(object sender, EventArgs e)
{
new AreYouSure().Show();
this.Show();
MenuBox.Items.Clear();
TotalBox.Items.Clear();
total.Clear();
ordertotal = 0;
}
}
}
Form2 (Confirmation)
namespace WindowsFormsApplication1 {
public partial class Confirmation : Form
{
public Confirmation()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Confirmation_Load(object sender, EventArgs e)
{
}
private void MenuBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
When clicking the 'Send Order' button the items from 'MenuBox' in form 1 need to be sent to the 'MenuBox' in form 2
OtherForm.OtherListbox.Items.Clear();
foreach(var itm in MenuBox.Items)
OtherForm.OtherListbox.Items.Add(itm);
Form1 (Main):
namespace WindowsFormsApplication1 {
public partial class RESTAURANT : Form
{
double soup = 2.49;
double ordertotal;
public RESTAURANT()
{
InitializeComponent();
}
private void RESTAURANT_Load(object sender, EventArgs e)
{
}
private void Add_Click(object sender, EventArgs e)
{
MenuBox.Items.Add("Soup");
TotalBox.Items.Add(String.Format("{0:C}", soup));
ordertotal += soup;
total.Text = Convert.ToString(String.Format("{0:C}", ordertotal));
}
private void TotalBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void PlaceOrder_Click(object sender, EventArgs e)
{
new AreYouSure().Show();
this.Show();
MenuBox.Items.Clear();
TotalBox.Items.Clear();
total.Clear();
ordertotal = 0;
}
}
}
Form2 (Confirmation)
namespace WindowsFormsApplication1 {
public partial class Confirmation : Form
{
public Confirmation()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Confirmation_Load(object sender, EventArgs e)
{
}
private void MenuBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
When clicking the 'Send Order' button the items from 'MenuBox' in form 1 need to be sent to the 'MenuBox' in form 2
It is better that the controls on your other form (ListBox, in this case) are set to Private by default.
In that case, you would either need to set the control's visibility to Public (bad form, in my opinion) or create a method in your other form to accept the parameters from your form.
Consider something like this:
public void ListBoxData(object[] array)
{
listBox1.Clear();
listBox1.AddRange(array);
}
To get the data or selected item information back to your main form, you would likewise create another public object that you could check, like the property below:
public object SelectedItem { get { return listBox1.SelectedItem; } }
I hope that is what you were looking for.
UPDATE:
Using the code you supplied in the post below, I can see you do not have anything in your Confirmation form to send data to, much less a way to pass that information.
If you had a ComboBox, you could do something like follows:
public partial class Confirmation : Form
{
private ComboBox comboBox1;
public void AddRange(object[] array)
{
comboBox1.Items.AddRange(array);
}
}
That does not place the ComboBox anywhere on your form. You would need to work that out.
With that done, I'm guessing you need to edit your PlaceOrder_Click routine:
private void PlaceOrder_Click(object sender, EventArgs e)
{
//new AreYouSure().Show();
//this.Show();
using (var obj = new Confirmation())
{
var list = new List<object>(MenuBox.Items.Count);
foreach (var o in MenuBox.Items)
{
list.Add(o);
}
obj.AddRange(list.ToArray());
if (obj.ShowDialog(this) == DialogResult.OK)
{
MenuBox.Items.Clear();
TotalBox.Items.Clear();
total.Items.Clear();
ordertotal = 0;
}
}
}
If you are struggling with this, you might need to look into some C# Windows "multiple forms" tutorials.
Here is a YouTube (that I did not sit all the way through): https://www.youtube.com/watch?v=qVVtCPDu9ZU
I am writing an application that passes gps data from a main form to a gps form at a constant interval (using a timer).
I've used the following tutorial to make a quick test:
http://www.codeproject.com/Articles/17371/Passing-Data-between-Windows-Forms
However, when I start the code no event is triggered. First I got a nullpointer. after adding the following lines I got rid of it:
if (GpsUpdated != null)
{
GpsUpdated(this, args);
}
Main form code:
public partial class Form1 : Form
{
// add a delegate
public delegate void GpsUpdateHandler(object sender, GpsUpdateEventArgs e);
// add an event of the delegate type
public event GpsUpdateHandler GpsUpdated;
int lat = 1;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Form_GPS form_gps = new Form_GPS();
form_gps.Show();
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
Debug.WriteLine("Timer Tick");
// instance the event args and pass it each value
GpsUpdateEventArgs args = new GpsUpdateEventArgs(lat);
// raise the event with the updated arguments
if (GpsUpdated != null)
{
GpsUpdated(this, args);
}
}
}
public class GpsUpdateEventArgs : EventArgs
{
private int lat;
// class constructor
public GpsUpdateEventArgs(int _lat)
{
this.lat = _lat;
}
// Properties - Viewable by each listener
public int Lat
{
get
{
return lat;
}
}
}
GPS form code:
public partial class Form_GPS : Form
{
public Form_GPS()
{
InitializeComponent();
}
private void Form_GPS_Load(object sender, EventArgs e)
{
Debug.WriteLine("GPS Form loaded");
Form1 f = new Form1();
// Add an event handler to update this form
// when the ID form is updated (when
// GPSUpdated fires).
f.GpsUpdated += new Form1.GpsUpdateHandler(gps_updated);
}
// handles the event from Form1
private void gps_updated(object sender,GpsUpdateEventArgs e)
{
Debug.WriteLine("Event fired");
Debug.WriteLine(e.Lat.ToString());
}
}
Can anyone point me in the right direction? What am I doing wrong?
Thanks in advance and with best regards.
You should pass an instance of Form1 to your Form_GPS for it to work properly. See the following changes:
public partial class Form_GPS : Form
{
public Form_GPS(Form1 owner)
{
InitializeComponent();
owner.GpsUpdated += new Form1.GpsUpdateHandler(gps_updated);
}
private void Form_GPS_Load(object sender, EventArgs e)
{
Debug.WriteLine("GPS Form loaded");
}
// handles the event from Form1
private void gps_updated(object sender,GpsUpdateEventArgs e)
{
Debug.WriteLine("Event fired");
Debug.WriteLine(e.Lat.ToString());
}
}
Now you need to a small change in Form1 as well:
private void Form1_Load(object sender, EventArgs e)
{
Form_GPS form_gps = new Form_GPS(this);
form_gps.Show();
timer1.Enabled = true;
}
Notice how you pass an instance of Form1 to Form_GPS in the constructor of Form_GPS using the self reference this.
Declaring the event as following solved the problem:
public static event GpsUpdateHandler GpsUpdated;
instead of:
public event GpsUpdateHandler GpsUpdated;
In this way the Form1 event can be called static, so no new instance is necessary.
I want to Use an instance of a class made in Form 1 in Form 2 (i changed it to a list for simplicity of example code:
Not only that, I want Form 2 to be able to modify it (Clear it at some point).
The advice I got was this, although I was not told how due to "no spoonfeeding allowed"
namespace automationControls.FileTime
{
public class Form_Main : Form
{
public List<string> folderList; //<---- i want to access this.....
private void button_showForm2_Click(object sender, EventArgs e)
{
Form_Log ConfirmBoxForm = new Form_Log(this);
ConfirmBoxForm.Show();
}
}
//form_Main opens form_Log
namespace automationControls.FileTime
{
public partial class Form_Log : Form
{
public Form_Log(Form_Main _f1)
{
InitializeComponent();
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
How.Do.I.AccessForm_Main.folderList.Clear();//<---- ............. in this function
}
}
}
Answered:In the constructor of Form_Log, store the reference to _f1 somewhere you can access it from elsewhere in Form_Log
Why don't you use the constructor that you have already added your form?
private Form_Main _mainForm;
public Form_Log(Form_Main _f1)
{
InitializeComponent();
_mainForm = _f1;
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
var myList = _mainForm.folderList;
}
Try This,
public class Form_Main : Form
{
public List<string> folderList; //<---- i want to access this.....
private void button_showForm2_Click(object sender, EventArgs e)
{
Form_Log ConfirmBoxForm = new Form_Log(this);
ConfirmBoxForm.Show();
}
}
Form log :
public partial class Form_Log : Form
{
private Form_Main _mainForm;
public Form_Log(Form_Main _f1)
{
InitializeComponent();
_mainForm = _f1;
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
_mainForm.folderList.Clear();
}
}
I don't know how advanced is your project but in this situation i would use delegates. Here is how i would do it:
public delegate void ModifyCollectionHandler(string parameter);
public delegate void ClearCollectionHandler();
public partial class Form1 : Form
{
public List<string> folderList;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form = new Form2()
form.ClearItem+=form_ClearItem;
form.AddItem+=form_AddItem;
form.DeleteItem+=form_DeleteItem;
}
void form_DeleteItem(string parameter)
{
if (folderList == null)
return;
folderList.Remove(parameter);
}
void form_AddItem(string parameter)
{
if (folderList == null)
folderList = new List<string>();
folderList.Add(parameter);
}
void form_ClearItem()
{
if (folderList != null)
folderList.Clear();
}
}
public partial class Form2 : Form
{
public event ModifyCollectionHandler AddItem;
public event ModifyCollectionHandler DeleteItem;
public event ClearCollectionHandler ClearItem;
public Form2()
{
InitializeComponent();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (ClearItem != null)
ClearItem();
}
}
I hope I helped you :)
Best regards
in the Form1 put this :
public static List<string> folderList;
you can simply call it from any form ex:Form2 like this :
From1.folderList.Clear();
I have a windows custom control with a picturebox and a button on it's default panel. This windows custom control will be added to a windows form. There is another windows form called form2. when the user double clicks on the custom control, it should load form2. in designer when i double clicked the custom control on the form, it creates a load() event for that custom control. But i need double click event, how this can be done?
here is the graphical view of what happens
Here is code in the control
[DefaultEvent("DoubleClick")]
public partial class cntrlImageLoader : UserControl
{
public cntrlImageLoader()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = Environment.SpecialFolder.MyPictures.ToString();
if (ofd.ShowDialog() == DialogResult.OK)
{
pbImage.Image = Image.FromFile(ofd.FileName);
}
}
private void pbImage_Click(object sender, EventArgs e)
{
this.cntrlImageLoader_DoubleClick(pbImage, e);
}
private void cntrlImageLoader_Load(object sender, EventArgs e)
{
}
private void cntrlImageLoader_DoubleClick(object sender, EventArgs e)
{
}
}
Here is the calling code on form1
private void cntrImLdrFront_DoubleClick(object sender, EventArgs e)
{
//this.cntrImLdrFront.pbImage.DoubleClick += new EventHandler(pbImage_DoubleClick);
}
FrmImageViewer f; // this is form2
private void pbImage_DoubleClick(object sender, EventArgs e)
{
f= new FrmImageViewer();
f.MdiParent = this.MdiParent;
f.Show();
}
Assign the attribute [DefaultEvent("DoubleClick")] at the class declaration.
[DefaultEvent("DoubleClick")]
public partial class MyControl : UserControl
{
}
This will creates event which you have set by default on double click of control at design time where you have placed your user control.
EDITED:
[DefaultEvent("LoadPicture")]
public partial class cntrlImageLoader : UserControl
{
public delegate void LoadPictureEventHandler(object sender, LoadPictureEventArgs e);
public event LoadPictureEventHandler LoadPicture;
private void pbImage_DoubleClick(object sender, EventArgs e)
{
if (LoadPicture != null)
{
LoadPictureEventArgs ev = new LoadPictureEventArgs();
LoadPicture(this, ev);
if (ev.Picture != null)
{
pbImage.Image = ev.Picture;
}
}
}
}
Create another class and give that class name to LoadPictureEventArgs
public class LoadPictureEventArgs : EventArgs
{
public Image Picture {get; set;}
public LoadPictureEventArgs(Image _picture)
{
Picture = _picture
}
public LoadPictureEventArgs()
: base()
{
}
}
HOW TO USE IT?
//FORM1
private void cntrImLdrFron_LoadPicture(object sender, LoadPictureEventArgs e)
{
Image img = null;
//LOAD YOUR IMAGE HERE
e.Picture = img;
}