Usercontrol为其他usercontrol设置TextBox文本

时间:2014-10-08 14:04:52

标签: c# user-controls

我有两个不同的usercontrol类。我试图通过另一个usercontrol为一个usercontrol设置文本框文本。获得我的财产是有效的,但该集合没有做任何事情。怎么解决这个?我已在下面发布了相关的代码段。

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

}

2 个答案:

答案 0 :(得分:1)

您获得的值是默认值,因为在构造 incidentCategoryChange之前只有一行。所以getter和setter都没有工作。

要在用户控件之间进行通信,一种可能性是以某种方式提供一个实例,其中TextBox(或任何其他属性)要获取/设置到另一个。

这可以通过将实例保存在某个地方来完成,例如,使用相同类的static属性(这要求只存在该用户控件的一个实例,但它& #39;很容易证明这个想法):

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

现在你可以做到

incidentCategory.Instance.TextBoxCategory = "test";

另一种解决方案是使用事件(参见this问题)。 incidentCategoryChange将订阅其他用户控件的事件CategoryValueChanged(string),并且在事件处理程序中可以更改TextBox的值。

答案 1 :(得分:0)

您是否尝试过将incCatChange.TextBoxCategory="test";设为incCatChange.TextBoxCategory.Text="test";