Adnan Maruf Ответов: 1

Как передавать значения между usercontrols в C#


So i've a Form1 with three UserControl's as UC1,UC2 & UC3. Form1 contains a Button, UC1 and UC3. Both UC1 & UC3 are initially hidden when the application runs and the Form1 button click event makes the UC1 visible. UC1 contains a panel and inside the UC1 load event I'm adding UC2 into the panel through panel.Controls.Add() method at application run time. UC2 contains a Button and the click event of this button makes UC3 visible in Form1. UC3 contain a textbox. Now when I click the UC2 Button, I want it to pass a string value to UC3 textbox. How do I do that? or generally I need a simple solution to send values from one UserControl to another UserControl.

Вот весь мой код...

Форма form1.в CS

namespace Problem
{
   public partial class Form1 : Form
  {

     public Form1()
     {
        InitializeComponent();
        uC11.u3Visible += UC11_u3Visible;// Event came from UC1
     }

     private void UC11_u3Visible(object sender, EventArgs e)
     {
        uC31.Visible = true;
        uC11.Visible = false;
     }

     private void button1_Click(object sender, EventArgs e)
     {
        uC11.Visible = true;
     }
  }
}

UC1.в CS

namespace Problem
{
  public partial class UC1 : UserControl
  {
      public event EventHandler u3Visible;//Declaring a public event
      public UC1()
      {
         InitializeComponent();
      }

      private void UC1_Load(object sender, EventArgs e)
      {
          UC2 xy = new UC2();
          xy.Name = "UsrCntrl2";
          xy.Location = new Point(18, panel1.Controls.Count * 73);
          panel1.Controls.Add(xy);// Adding UC2 in UC1
          xy.open += Xy_open;// UC2 button click event
      }

      private void Xy_open(object sender, EventArgs e)
      {
          EventHandler handler = u3Visible;
          if (handler != null)
          {
              handler(this, new EventArgs());// Creating another event to make UC3 visible 
              //upon button click from UC2.
          }
      }
   }
}

Файлов uc2.в CS

namespace Problem
{
   public partial class UC2 : UserControl
 {

    public event EventHandler open;//Declaring a public event
    public UC2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        EventHandler handler = open;
        if (handler != null)
        {
            handler(this, new EventArgs());// Button click sending this event
        }
        string text = "Hello There!";// "I want this string to pass into UC3 textbox"
        var ass = new UC3(text);


    }
  }
}

МК UC3.в CS

namespace Problem
{
   public partial class UC3 : UserControl
{
    public UC3()
    {
        InitializeComponent();
    }
    public UC3(string text)
    {
        InitializeComponent();
        TB.Text = text;// why textbox not showing this value?
        MessageBox.Show(text);// while this MessageBox showing it!
    }
  }
}


Что я уже пробовал:

Я застрял с этой проблемой на столько часов. Я пробовал гуглить, чтобы найти соответствующие решения, но ничего такого полезного не придумал. Так что пришлось выложить его здесь. Любая помощь будет очень признательна. Заранее спасибо!

F-ES Sitecore

Generally speaking, you don't. Components should be self-contained with no reliance or knowledge about about thing else. If you want one component to change something about itself based on the actions of another component then have the component that has changed raise an event like "XYZButtonClicked". The control that needs to update itself should provide a method that allows this like "UpdateABCText", along with any parameters it needs to update the component like new text etc. The parent form that the controls are on will subscribe to the XYZButtonClicked event provided by the first component and when it is received it will then call the UpdateABCText method of the second component. If data needs to be passed along then the component raising the event can pass that with the event it raises, the parent form reads that data and passes it as params to the method in the second control.

1 Ответов

Рейтинг:
2

Manoj Kumar Choubey

Вместо визуального true / false со стороны сервера, сделайте это со стороны клиента с помощью css


F-ES Sitecore

Я не думаю, что это веб-сайт

Adnan Maruf

Спасибо за ваш ответ! но это приложение C# Winform, а не Веб-страница :)