MainControl의 새 인스턴스에 새 usercontrol을 추가하고 있습니다. 이 새 인스턴스는 절대로 표시되지 않으므로 볼 수 없습니다. 현재 MainForm의 인스턴스를 UserControl 생성자에 전달하는 가장 간단한 방법으로이 문제를 피하려면 해당 인스턴스를 UserControl의 전역 변수에 저장하고 두 개의 usercontrols를 전환해야 할 때 해당 인스턴스를 사용하십시오. UserControl1.cs
public class UserControl1
{
MainForm _current;
public UserControl1(MainForm f)
{
InitializeComponent();
_current = f;
}
private void btnProceed_Click(object sender, EventArgs e)
{
.....
UserControl2 u2 = new UserControl2();
_current.panelMain.Controls.Add(u2);
u2.listView1.Items.Add(new ListViewItem(new[]{
name,
email,
phone,
color}));
}
}
에서 MainForm.cs에서
(첫 번째 UserControl을 만들 때)
UserControl1 uc = new UserControl1(this);
.....
이 제대로 다른 작업에 대한 처리 문제가 될 것입니다. MainForm이 필요할 때 표시 할 사용자 정의 컨트롤을 결정하도록 응용 프로그램을 다시 디자인하는 것이 좋습니다.
이 접근 방식에서는 사용자가 UserControl1을 클릭 할 때 MainForm.cs에서 이벤트를 사용하여 MainForm에서이 정보를 얻을 수 있습니다.CS
UserAdded 새 사용자에 대해 정보를받은 MainForm하는 방법입니다
UserControl1 uc = new UserControl1();
uc.UserClick += UserAdded;
.....
하지만 클래스 UserInfoArgs
public void UserAdded(UserControl1 sender, UserInfoArgs args)
{
sender.Hide();
UserControl2 u2 = new UserControl2();
this.panelMain.Controls.Add(u2);
u2.listView1.Items.Add(new ListViewItem(new[]{
args.name,
args.email,
args.phone,
args.color}));
}
그리고 UserControl1을 당신이 대리자, 이벤트를 추가 할 때 이벤트를 마련 새 사용자에 대한 정보를 MainForm과 통신해야합니다.
public class UserControl1
{
public delegate void onClick(UserControl1 sender, UserInfoArgs args);
public event onClick UserClick;
....
private void btnProceed_Click(object sender, EventArgs e)
{
UserInfoArgs args = new UserInfoArgs()
{
name = tbName.Text,
email = tbEmail.Text,
phone = tbPhone.Text,
color = tbColor.Text
};
if(UserClick != null)
UserClick(this, args);
}
public class UserInfoArgs
{
public string name {get;set;}
public string email {get;set;}
public string phone {get;set;}
public string color {get;set;}
}
MainForm의 새 인스턴스를 만들고 해당 인스턴스에 새 usercontrol을 추가했기 때문에. _f1.Show(); _를 추가하면 표시됩니다. 그러나 MainCont의 기존 인스턴스에 새 usercontrol을 추가하려고한다고 가정합니다. – Steve
@steve 예 .... MainForm의 새 인스턴스를 만들지 않고 컨트롤을 추가하려면 어떻게해야합니까? – BiKe
가장 간단한 방법으로 현재 MainForm의 인스턴스를 UserControl 생성자에 전달하면 해당 인스턴스를 UserControl의 전역 변수에 저장하고 두 개의 usercontrol을 전환해야 할 때 해당 인스턴스를 사용합니다. 이것은 다른 작업을 올바르게 처리하기 위해 문제가됩니다. MainForm이 필요할 때 표시 할 사용자 정의 컨트롤을 결정하도록 응용 프로그램을 다시 디자인하는 것이 좋습니다. – Steve