Sybren
Sybren

Reputation: 1079

Usercontrol set TextBox text for other usercontrol

I have two diffrent usercontrol classes. I'm trying to set the textbox text for one usercontrol by another usercontrol. The get of my property is working but the set doesn't do anything. How to solve this? I've posted the related code snippets below.

incidentCategorySearchControl.cs

     public partial class incidentCategorySearchControl : UserControl
     {

     private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
      {


       incidentCategoryChange incCatChange = new incidentCategoryChange();
       //textBox1.Text = incCatChange.TextBoxCategory; // works
       incCatChange.TextBoxCategory="test"; // doesn't work

      }
    }

incidentCategoryChange.cs

    public partial class incidentCategoryChange : UserControl
    {
    public incidentCategoryChange()
    {
        InitializeComponent();
    }

    public string TextBoxCategory
    {
        get { return incidentCategoryTextBox.Text; }
        set { incidentCategoryTextBox.Text = value; }
    }

}

Upvotes: 0

Views: 1640

Answers (2)

Sinatr
Sinatr

Reputation: 21989

The value you get is default value, because just a line before you have constructed incidentCategoryChange. So both getter and setter aren't working.

To communicate between user controls one possibility would be to provide somehow an instance of one, which TextBox (or any other property) you want to get/set, to another.

This can be done by having instance saved somewhere, to example, by using static property of same class (this require that only one instance of that user control is exists, but it's very simple to demonstrate idea):

public partial class incidentCategoryChange : UserControl
{
    public static incidentCategoryChange Instance {get; private set;}

    public incidentCategoryChange()
    {
        InitializeComponent();
        Instance = this;
    }

    public string TextBoxCategory
    {
        get { return incidentCategoryTextBox.Text; }
        set { incidentCategoryTextBox.Text = value; }
    }
}

Now you can do

incidentCategory.Instance.TextBoxCategory = "test";

Another solution would be to use events (see this question). incidentCategoryChange will subscribe to event CategoryValueChanged(string) of other user control and in event handler can change the value of TextBox.

Upvotes: 1

user3267755
user3267755

Reputation: 1070

Have you tried setting incCatChange.TextBoxCategory="test"; to incCatChange.TextBoxCategory.Text="test";

Upvotes: 0

Related Questions