c#获取特定表单以更改特定值

时间:2015-04-21 02:31:47

标签: c#

如何获取特定的打开表单并更改表单的特定属性的值。我正在尝试将Form转换为特定表单以更改该特定表单的值

我根据ID

打开了多个使用动态名称打开的表单
public UserChatFrm varUserChatFrm;
public void UserChatFrmOpener(string sendToEmpID)// function that will open multiple chat form depending n the senderid
    {
        if (Application.OpenForms["UserChatFrm" + sendToEmpID] == null)
        {
            varUserChatFrm = new UserChatFrm(sendToEmpID);
            varUserChatFrm.Name = "UserChatFrm" + sendToEmpID;
            varUserChatFrm.Tag = "UserChatFrm" + sendToEmpID;
            varUserChatFrm.lblName.Text = sendToEmpID;
            //varUserChatFrm.Text = sendToEmpID;
            varUserChatFrm.MdiParent = Application.OpenForms["MainFrm"];
            varUserChatFrm.Show();
        }
        varUserChatFrm.BringToFront();
    }

这是打开的表格

UserChatFrm UserChatFrm11 - > textbox1

UserChatFrm UserChatFrm12 - > textbox1 //我想更改此

的文本

UserChatFrm UserChatFrm13 - > textbox1

UserlistFrm UserlistFrm - > listview

以下是我获取该特定表单的代码

FormCollection fc = Application.OpenForms;
foreach (Form frm in fc)
{
    if (frm.Name == "UserChatFrm" + rdr["emp_sys_id"].ToString())// this is querried in the database to naming specific form sample "UserChatFrm11"
    {
         UserChatFrm varUsrchat = frm; // not working error which has missing cast?
         varUsrchat.textbox1.text = "sample"; // I want to change the value of specific 

 // or something like this
   Application.OpenForms["UserChatFrm" + "12"].chatbox1.text = "sample"; //not working
   }
 }

你能说出我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

我不喜欢你尝试更新表单的方式,你可以为这种方法找到不同的解决方案,我理想的方法是创建接口并为你想要更新它的每个表单实现它,然后将表单转换为界面和更新表单:

public interface IFormUpdator<TModel> where TModel : class
{
    void UpdateForm(TModel model)
}

然后为每个类实现此接口:

public Form UserChatFrm : IFormUpdator<string>
{

  public void UpdateForm(string model)
  {
     this.textbox1.text = model;
  }

  .....

}

然后对要更新它们的所有其他表单执行相同操作

您可以像这样更新表单:

Application.OpenForms.OfType<IFormUpdator<string>>()
   .ForEach(frm => frm.Update("Sample"));