Calling Another user control from one user control - c#

I have two user controls usercontrol_1 and usercontrol_2, using a click event i am bring in usercontrol_1 to a panel called panel_screen on my main form.
private void btn_Click(object sender, EventArgs e)
{
if (!panel_screen.Controls.Contains(usercontrol_1.Instance))
{
panel_screen.Controls.Add(usercontrol_1.Instance);
usercontrol_1.Instance.Dock = DockStyle.Fill;
usercontrol_1.Instance.BringToFront();
}
else
usercontrol_1.Instance.BringToFront();
}
Similarly i wanna bring usercontrol_2 to the same panel on the main form using a button (click event) on usercontrol_1.
How do i do this? any help would be appreciated.

I'm not sure where you are having problem, I think the way you are using usercontrol_1.Instance might cause the issue.
I have working example here, you can try it.
private void btn_Click(object sender, EventArgs e)
{
bool userControlIsAlreadyInPanel = false;
//assuming you are cheking if usercontrol_1 is already there on panel
// you don't want to create new usercontrol, but just bring existing control to the front
foreach(UserControl control in panel_screen.Controls)
{
if (control.GetType() == typeof(usercontrol_1))
{
userControlIsAlreadyInPanel = true;
control.BringToFront();
}
}
if(!userControlIsAlreadyInPanel)
{
usercontrol_1 instane = new usercontrol_1();
panel_screen.Controls.Add(instane);
instane.Dock = DockStyle.Fill;
instane.BringToFront();
}
}
output

namespace WindowsFormsApp1
{
public delegate void MyEventDelegate(object sender, string name);
public partial class Form1 : Form
{
usercontrol_1 _ctrl1 = null;
usercontrol_2 _ctrl2 = null;
public Form1()
{
InitializeComponent();
_ctrl1 = new usercontrol_1();
_ctrl1.Dock = DockStyle.Fill;
_ctrl1.userControlButtonClicked += userControlButtonClicked;
_ctrl2 = new usercontrol_2();
_ctrl2.Dock = DockStyle.Fill;
_ctrl2.userControlButtonClicked += userControlButtonClicked;
this.Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
userControlButtonClicked(_ctrl1, "1");
}
private void userControlButtonClicked(object sender, string name)
{
panel1.Controls.Clear();
if (sender.Equals(_ctrl1))
{
panel1.Controls.Add(_ctrl2);
}
else if (sender.Equals(_ctrl2))
{
panel1.Controls.Add(_ctrl1);
}
}
}
}
namespace WindowsFormsApp1
{
public partial class usercontrol_1 : UserControl
{
public event MyEventDelegate userControlButtonClicked;
public usercontrol_1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MyEventDelegate med = userControlButtonClicked;
if (med != null)
{
med(this, "1");
}
}
}
}
namespace WindowsFormsApp1
{
public partial class usercontrol_2 : UserControl
{
public event MyEventDelegate userControlButtonClicked;
public usercontrol_2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MyEventDelegate med = userControlButtonClicked;
if (med != null)
{
med(this, "2");
}
}
}
}

Related

C#-Winforms-How to use instance objects in different subforms?

I have a "MainForm" and a "GraphicsForm". Clicking "New" on the main form, a "GraphicsForm" will be created.
The problem is that when I create multiple "GraphicsForm", and when I want to save the content of one of the "GraphicsForm", I need to clicking "Save" on the "MainForm" and the program will save the content of the active "GraphicsForm" to a file, I don't know how to pass the content of this "GraphicsForm" to "MainForm" for storage.
MainForm.cs
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private ToolStripMenuItem _winMenuItem = new ToolStripMenuItem();
private GraphicsForm _graphicsForm;
private int _counter = 1;
private void New_Click(objec sender, EventArgs e)
{
_winMenuItem.Name = "Win";
_winMenuItem.Text = "Windows";
int item = MainMenuStrip.Items.IndexOf(_winMenuItem);
if (item == -1)
{
MainMenuStrip.Items.Add(_winMenuItem);
MainMenuStrip.MdiWindowListItem = _winMenuItem;
}
_graphicsForm = new GraphicsForm();
_graphicsForm.Name = string.Concat("Win_", _counter.ToString());
_graphicsForm.Text = _graphicsForm.Name;
_graphicsForm.MdiParent = this;
_graphicsForm.Show();
_graphicsForm.WindowState = FormWindowState.Maximized;
_counter++;
}
private void Save_Click(object sender, EventArgs e)
{
... // Problem here
}
private void Open_Click(object sender, EventArgs e)
{
... // Problem here
}
}
GraphicsForm.cs
public partial class GraphicsForm : Form
{
//StorageDoc is a class to manage all the graphics drawn by the user in the form.
private StorageDoc _storageDoc = new StotageDoc();
public GraphicsForm()
{
InitializeComponent();
}
private Canvas_MouseDown()
{
}
private Canvas_Paint()
{
}
...
Because MainForm is a MDI form, it is easy to use ActiveMdiChild to get the active child form.
class MainForm : Form
{
public void OnSaveButtonClick(object sender, EventArgs e)
{
if(ActiveMdiChild is GraphicsForm g)
Save(g);
}
}
I'm sure this has been answered before but basically, you pass in an instance of the 'data storage' to the new form.
interface ISaveForm
{
void Save();
}
class MainForm
{
private DataStorage _dataStorage;
private ICollection<ISaveForm> _forms = new List<ISaveForm>();
public void OnNew()
{
var subForm = new GraphicsForm(_dataStorage);
subForm.Show();
_forms.Add(subForm);
}
public void OnSave()
{
foreach(var form in _forms)
{
form.Save();
}
}
}
class GraphicsForm : Form,ISaveForm
{
private DataStorage _dataStorage;
public GraphicsForm(DataStorage dataStorage)
{
_dataStorage = dataStorage;
}
public void Save()
{
}
}

c# change panel color from another form

I'm stuck with the following thing.
I want to change the panel color from another Form(ColorForm).
Is it possible?
Code From the MainForm:
public void upperpanel_Paint(object sender, PaintEventArgs e)
{
}
I don't know how to access that upperpanel_Paint in my ColorForm.
I'm opening ColorForm From SettingsForm
Mainform > SettingsForm > ColorForm
public partial class SettingsForm : Form
{
public static event ColourSettingChangedDelegate ColourSettingsChangedEvent;
public delegate void ColourSettingChangedDelegate(Color color);
List<string> adreses;
List<string> bookmarki;
void SelectColour()
{
using (ColorForm colourForm = new ColorForm())
{
if (colourForm.ShowDialog() == DialogResult.OK)
{
//Update colour setting and fire event
OnColourSettingsChanged(colourForm.SelectedColor);
}
}
}
public SettingsForm(List<string> adr, List<string> s)
{
InitializeComponent();
adreses = adr;
bookmarki = s;
}
private void Historyb_Click(object sender, EventArgs e)
{
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(HistoryForm))
{
form.Activate();
return;
}
}
HistoryForm hf1 = new HistoryForm(adreses);
hf1.Show();
}
private void Bookmarksb_Click(object sender, EventArgs e)
{
BookmarksForm booklist = new BookmarksForm();
booklist.SetAllBookmarks(bookmarki);
booklist.ShowDialog();
}
private void Colorb_Click(object sender, EventArgs e)
{
SelectColour();
}
private void OnColourSettingsChanged(Color color)
{
if (ColourSettingsChangedEvent != null)
ColourSettingsChangedEvent(color);
}
}
Code from ColorForm:
public partial class ColorForm : Form
{
public ColorForm()
{
InitializeComponent();
}
private void Panelcolor_Click(object sender, EventArgs e)
{
ColorDialog colorDlg = new ColorDialog();
colorDlg.AllowFullOpen = true;
colorDlg.AnyColor = true;
if (colorDlg.ShowDialog() == DialogResult.OK)
{
upperpanel.BackColor = colorDlg.Color;
}
}
}
Thank you!
Perhaps it would be better to fire a global event when the settings change, or the particular form colour setting changes, and listen for that event on the form where you need to take action.
for example see this pseudo code:
ColourForm:
Form used just to pick a colour, and store the result in a property.
class ColourForm
{
public Color SelectedColor {get;set;}
private void Panelcolor_Click(object sender, EventArgs e)
{
ColorDialog colorDlg = new ColorDialog();
colorDlg.AllowFullOpen = true;
colorDlg.AnyColor = true;
if (colorDlg.ShowDialog() == DialogResult.OK)
{
this.SelectedColor = colorDlg.Color;
}
}
void Cancel()
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
void Save()
{
this.DialogResult = DialogResult.OK;
this.Close();
}
}
SettingsForm:
The main form for updating settings, this creates a colour picker form and saved the settings and fires an event if the dialog result of the colour form is an 'ok' result.
class SettingsForm
{
public static event ColourSettingChangedDelegate ColourSettingsChangedEvent;
public delegate void ColourSettingChangedDelegate(Color color);
void SelectColour()
{
using (ColourForm colourForm = new ColourForm())
{
if (colourForm.ShowDialog() == DialogResult.OK)
{
//Update colour setting and fire event
OnColourSettingsChanged(colourForm.SelectedColour);
}
}
}
private void OnColourSettingsChanged(Color color)
{
if (ColourSettingsChangedEvent!=null)
ColourSettingsChangedEvent(color);
}
}
On you Main Form:
The Main form listens for a settings / colour changed event and changes the panel colour to the colour specified in the event when it fires.
class MainForm()
{
//Constructor
MainForm()
{
SettingsForm.ColourSettingsChangedEvent += ColourSettingsChanged;
}
void ColourSettingsChanged(Color color)
{
upperpanel.BackColor = color;
}
}
it would be better to have some kind of settings manager class than have the event on the settings form itself but you should get the idea

How I can write code in button's event of a form, from another form in a same name space?

I write code which get my data source data from a gridview in this form. But I can't find a way to change my data and save my context. Because my savebtn is on another form.
Here is my code:
namespace FactorEntity
{
public partial class CustomerResearchForm : MetroFramework.Forms.MetroForm
{
FactorEntities contex;
public CustomerResearchForm()
{
InitializeComponent();
}
private void CustomerResearchForm_Load(object sender, EventArgs e)
{
}
private void CResearchGrid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
CustomerUpdateAndDelete CustomerUpdateAndDelete = new CustomerUpdateAndDelete();
contex = new FactorEntities();
{ var sendergrid=(DataGridView)sender;
int customercode = Convert.ToInt32(sendergrid.Rows[e.RowIndex].Cells[1].Value);
var customer = from _customer in contex.tblCustomers where
_customer.CustomerCode==customercode select _customer;
CustomerUpdateAndDelete.tblCustomerBindingSource.DataSource = customer.ToList();
CustomerUpdateAndDelete.Show();
if (CustomerUpdateAndDelete.tblCustomerBindingNavigatorSaveItem.CheckOnClick == true)
{
contex.SaveChanges();
}
}
}
}
}
And this is my CustomerUpdateAndDelete form which tblCustomerBindingNavigatorSaveItem is here
namespace FactorEntity
{
public partial class CustomerUpdateAndDelete : MetroFramework.Forms.MetroForm
{
public CustomerUpdateAndDelete()
{
InitializeComponent();
}
private void CustomerUpdateAndDelete_Load(object sender, EventArgs e)
{
}
private void tblCustomerBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
}
}
}

Custom controls and event handling?

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;
}

User control and how to get button events from form

i created user control which looks like this:
and code behind looks like:
using System;
using System.Windows.Forms;
namespace Controlls
{
public partial class Toolbar : UserControl
{
public Toolbar()
{
InitializeComponent();
}
private void pbNaprej_Click(object sender, EventArgs e)
{
}
private void pbNazaj_Click(object sender, EventArgs e)
{
}
private void pbNovo_Click(object sender, EventArgs e)
{
}
private void bpbBrisi_Click(object sender, EventArgs e)
{
}
private void pbPotrdi_Click(object sender, EventArgs e)
{
}
private void txtOd_TextChanged(object sender, EventArgs e)
{
}
}
}
now i move this UC to form but there is a problem. How to get this events from UC. I need to implement click events for buttons in form where i use this user control. What i can see is that i can use it like one component and i can not get separate buttons from it.
Add 2 event handlers for yor control, and subscribe to the toobox event at the place you use it:
using System;
using System.Windows.Forms;
namespace Controlls
{
public enum ToolboxButtonType { Potrdi, Brisi, Novo, Nazaj, Naprej }
public partial class Toolbar : UserControl
{
public Toolbar()
{
InitializeComponent();
}
private void pbNaprej_Click(object sender, EventArgs e)
{
OnToolboxClick(ToolboxButtonType.Naprej);
}
private void pbNazaj_Click(object sender, EventArgs e)
{
OnToolboxClick(ToolboxButtonType.Nazaj);
}
private void pbNovo_Click(object sender, EventArgs e)
{
OnToolboxClick(ToolboxButtonType.Novo);
}
private void bpbBrisi_Click(object sender, EventArgs e)
{
OnToolboxClick(ToolboxButtonType.Brisi);
}
private void pbPotrdi_Click(object sender, EventArgs e)
{
OnToolboxClick(ToolboxButtonType.Potrdi);
}
private void txtOd_TextChanged(object sender, EventArgs e)
{
OnTextChanged(txtOd.Text);
}
}
private OnToolboxClick(ToolboxButtonType button)
{
if (ToolboxClick != null)
{
ToolboxClick(this, new ToolboxClickEventArgs(button));
}
}
private OnTextChanged(string text)
{
if (ToolboxTextChanged!= null)
{
ToolboxTextChanged(this, new ToolboxTextChangedEventArgs(text));
}
}
public class ToolboxTextChangedEventArgs: EventArgs
{
public string Text { get; private set; }
public ToolboxClickEventArgs(string text) { Text = text; }
}
public class ToolboxClickEventArgs : EventArgs
{
public ToolboxButtonType Button { get; private set; }
public ToolboxClickEventArgs(ToolboxButtonType button) { Button = button; }
}
public event EventHandler<ToolboxClickEventArgs> ToolboxClick;
public event EventHandler<ToolboxTextChangedEventArgs> ToolboxTextChanged;
}
For example:
//Toolbar toolbar = new Toolbar();
toolbar.ToolboxTextChanged += (s, e) => { btn1.Text = e.Text; };
toolbar.ToolboxClick += (s, e) =>
{
swith(e.Button)
{
case ToolboxButtonType.Brisi: //
break;
default:
break;
}
};
You need to create event in MainForm class and generarate it in hand mode.
If you also draw your icons on canvas or smth, you need to handle onClick your MainForm, than calculate mouse click position, and generate event that you were create.
If it amount of buttons or smth that has their own onClick events, you can hang on this buttons event the action that will generate your even in main form.
Answer what approach you use, and I past some code.
ADDED:
public partial class Toolbar : UserControl
{
public Toolbar()
{
InitializeComponent();
}
public enum ToolBarCommands
{
Naprej, Nazaj, Novo
}
public Action<object, ToolBarCommands> MenuItemClick;
private void pbNaprej_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
MenuItemClick(this, ToolBarCommands.Naprej);
}
private void pbNazaj_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
MenuItemClick(this, ToolBarCommands.Nazaj);
}
private void pbNovo_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
MenuItemClick(this, ToolBarCommands.Novo);
}
}
How to use it? easy:
// Define section
var toolbar = new Toolbar();
toolbar.MenuItemClick += MenuItemClickHandler;
...
MenuItemClickHandler(object sender, Toolbar.ToolBarCommands item)
{
switch(item)
{
case Toolbar.ToolBarCommands.Naprej:
// Naperej handler
break;
case Toolbar.ToolBarCommands.Nazaj:
// Nazaj handler
break;
case Toolbar.ToolBarCommands.Novo:
// Novo handler
break;
}
}
ADDED:
If names of your buttons same as enum members you can cut this part of code:
private void pbNaprej_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
MenuItemClick(this, ToolBarCommands.Naprej);
}
private void pbNazaj_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
MenuItemClick(this, ToolBarCommands.Nazaj);
}
private void pbNovo_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
MenuItemClick(this, ToolBarCommands.Novo);
}
It will look's like one method (hang this method to all your menu element events)
private void pbItem_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
{
ToolBarCommands command;
var res = ToolBarCommands.TryParse(((Button)sender).Name, command)
if(res == true)
MenuItemClick(this, command);
}
}

Categories

Resources