在用户控件中填充 ComboBox

Populating ComboBox in User Control

我试图了解窗体中 UserControl 的生命周期。以下是一个测试项目,但是,UserControl1(通过设计器添加)正在显示,但没有数据填充到 ComboBox1 中。 UserControl2 不显示(在 Form1 OnLoad 事件中添加),并且 UserControl3 不通过 Button 事件显示。任何帮助将不胜感激。

这是 Form1 的代码:

using System;
using System.Windows.Forms;

namespace ComboBoxTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            using (UserControl1 ucCtrl = new UserControl1())
            {
                groupBox2.Controls.Add(ucCtrl);
                ucCtrl.BringToFront();
            }
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            using (UserControl1 ucCtrl = new UserControl1())
            {
                groupBox3.Controls.Clear();
                groupBox3.Controls.Add(ucCtrl);
                ucCtrl.BringToFront();
            }
        }
    }
}

这是 UserControl1 的代码

using System;
using System.Data;
using System.Windows.Forms;

namespace ComboBoxTest
{
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
            PopulateComboBox();
        }

        private void PopulateComboBox()
        {
            using (DataTable dtData = new DataTable())
            {
                DataColumn dtCol;
                DataRow dtRow;

                dtCol = new DataColumn
                {
                    DataType = typeof(Int32),
                    ColumnName = "Index"
                };
                dtData.Columns.Add(dtCol);

                dtCol = new DataColumn
                {
                    DataType = typeof(String),
                    ColumnName = "Option"
                };
                dtData.Columns.Add(dtCol);

                for (int xI = 0; xI < 5; xI++)
                {
                    dtRow = dtData.NewRow();

                    dtRow["Index"] = xI;
                    dtRow["Option"] = "Option " + Convert.ToString(xI);
                    dtData.Rows.InsertAt(dtRow, xI);
                }
                comboBox1.DataSource = dtData;
                comboBox1.DisplayMember = "Option";
                comboBox1.ValueMember = "Index";
                comboBox1.SelectedIndex = 0;
            }
        }
    }
}

UserControl1 (added via the Designer) is showing but no data populated in ComboBox1. UserControl2 doesn't show (added at Form1 OnLoad event), and UserControl3 doesn't show via a Button event

根本问题是因为您将构造包装在 using 语句中。例如:

 using (UserControl1 ucCtrl = new UserControl1())
 {
    groupBox2.Controls.Add(ucCtrl);
    ucCtrl.BringToFront();
 }

要解决您的问题,只需删除 using 语句,因为当它到达 using 的末尾时,用户控件将被丢弃。

例如上面的示例(using 已删除):

 UserControl1 ucCtrl = new UserControl1();
 groupBox2.Controls.Add(ucCtrl);
 ucCtrl.BringToFront();