当我的用户控件父项是表单时,我希望通过按钮单击从另一个调用usercontrol函数/方法...
形式;我加载并添加用户控件:
//Controls enum holding names of all our user controls
public enum ControlsEnum
{
SPLASH_CONTROL,
MAIN_CONTROL,
CATEGORY_CONTROL,
}
public partial class MainForm : Form
{
//Dictionary that holds all our instantiated user controls.
private IDictionary<ControlsEnum, Control> controls = new Dictionary<ControlsEnum, Control>();
public MainForm()
{
InitializeComponent();
//When the program runs for the first time, lets call the ShowControl method that
//will show the first control
ShowControl(ControlsEnum.SPLASH_CONTROL);
}
public void ShowControl(ControlsEnum ctrl)
{
Control new_ctrl = null;
//If our dictionary already contains instance of
if (controls.ContainsKey(ctrl))
{
new_ctrl = controls[ctrl];
}
else
{
new_ctrl = CreateControl(ctrl);
controls[ctrl] = new_ctrl;
}
new_ctrl.Parent = this;
new_ctrl.Dock = DockStyle.Fill;
new_ctrl.BringToFront();
new_ctrl.Show();
}
private Control CreateControl(ControlsEnum ctrl)
{
switch (ctrl)
{
case ControlsEnum.SPLASH_CONTROL:
return new Splash_uc();
case ControlsEnum.MAIN_CONTROL:
return new Main_uc();
case ControlsEnum.CATEGORY_CONTROL:
return new Categoty_uc();
default:
return null;
}
}
并在Category_uc中:
private void btn_categorySave_Click(object sender, EventArgs e)
{
// i want refresh datagridview and add new category to list by save in database
}
并在main_uc中:
private void datagridview_Refresh()
{
//rebind datagridview datasource
// i want call this function from "category_uc" when click on Save Button
}
请帮帮我! TNX;
答案 0 :(得分:1)
您可以向控件添加事件:
class Categoty_uc
{
public event EventHandler ButtonClicked;
protected OnButtonClicked()
{
var tmp = ButtonClicked;
if(tmp != null)
{
tmp(this, EventArgs.Empty);
}
}
private void btn_categorySave_Click(object sender, EventArgs e)
{
OnButtonClicked();
}
}
然后以你的主要形式:
private Main_uc main_uc = null;
private Control CreateControl(ControlsEnum ctrl)
{
Control ret = null;
switch (ctrl)
{
case ControlsEnum.CATEGORY_CONTROL:
{
if(main_uc != null)
{
ret = new Categoty_uc();
((Categoty_uc)ret).ButtonClicked += (sender, e) =>
{main_uc.datagridview_Refresh();}
}
else
{
throw new Exception("Create Main_uc first!");
}
}
break;
case ControlsEnum.MAIN_CONTROL:
{
if(main_uc == null)
{
main_uc = new Main_uc();
}
ret = main_uc;
}
}
return ret;
}