如何在没有构造函数的情况下将数据绑定到usercontrol?

时间:2017-04-06 08:42:39

标签: c# winforms user-controls wpf-controls

我使用了此链接中的用户控件https://www.codeproject.com/articles/739902/how-to-easily-host-wpf-control-inside-windows-form 我只能在构造函数中的此用户控件中加载数据但是我想从其他方法调用它但是我失败了有没有办法? 建设是

public Getstarted()
{
   InitializeComponent();
   List<Employee2> employees = new List<Employee2>();
   try
   {
       con = new SqlConnection(cs.DBConn);
       con.Open();
       cmd = new SqlCommand("SELECT Participant.ParticipantName, MeetingParticipant.Title, Participant.ParticipantId FROM            MeetingParticipant INNER JOIN Participant ON MeetingParticipant.ParticipantId = Participant.ParticipantId INNER JOIN Meeting ON MeetingParticipant.MeetingId = Meeting.MeetingId where Meeting.Statuss='Open'", con);
       rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            while (rdr.Read() == true)
            {
                employees.Add(new Employee2() { Name = rdr[0].ToString(), Title = rdr[1].ToString(), Id = rdr[2].ToString()});
            }
            con.Close();
   }
   catch (Exception ex)
   {
       MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
   this.comboBoxWithGrid_WinformsHost1.Employee2s = employees;
}

我在按钮事件中尝试了这个但是失败了

private void MyMethod()
{       
    List<Employee2> employees = new List<Employee2>();
    try
    {
       con = new SqlConnection(cs.DBConn);
       con.Open();
       cmd = new SqlCommand(" SELECT Participant.ParticipantName, MeetingParticipant.Title, 
       Participant.ParticipantId FROM            MeetingParticipant 
           INNER JOIN 
             Participant ON MeetingParticipant.ParticipantId = 
             Participant.ParticipantId INNER JOIN Meeting ON 
             MeetingParticipant.MeetingId = Meeting.MeetingId where 
             Meeting.Statuss='Open'", con);
      rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

      while (rdr.Read() == true)
      {
          employees.Add(new Employee2() { Name = rdr[0].ToString(), Title = rdr[1].ToString(), Id = rdr[2].ToString()});     
      }
      con.Close();
    }
    catch (Exception ex)
    {
       MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
        this.comboBoxWithGrid_WinformsHost1.Employee2s = employees;
}

这是我在这里的第一个问题而且我是这个部门的新手如果遗漏了请尝试理解我的限制谢谢。

1 个答案:

答案 0 :(得分:0)

这不是我问题的直接答案,但我解决了我的问题 使用这一行

        this.comboBoxWithGrid_WinformsHost1.Employee2s.AddRange(employees);