Designer在DataGridViewComboBoxColumn

时间:2016-08-07 22:33:15

标签: c# datagridview datagridviewcombobox

我有一个继承自DataGridView的自定义控件。它有预定义的列。

其中一列是ComboBox列。我想要它以便用户可以选择一天中的一小时,因此它绑定到一个数据源,该数据源是一个整数数组,从0到24。

在设计时一切都很好(当我将控件放到表单上时)。我得到的问题是运行时,设计者尝试两次添加数据源,然后导致错误。

以下是显着的代码:

//Constructor for teh usercontrol        
    public OutageGrid()
    {
        base.AutoGenerateColumns = false;       //Hidden from intellisense, but needed to prevent columns being duplicated by the designer.
        InitializeComponent();
    }

private int[] Hours = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };


        /// <summary>
    /// This is called after the usercontrol is added to another container (form).  This is used to add the columns to the
    /// control, to avoid the issue where the columns get duplicated at runtime.
    /// </summary>
    protected override void InitLayout()
    {
        //base.InitLayout();
        SetColumns();
    }
    private void SetColumns()
    {
        base.Columns.Clear();

        base.Columns.Add("ID", "ID");
        base.Columns.Add("IAPCode", "IAPCode");
        base.Columns.Add("Venture", "Venture");

        DataGridViewComboBoxColumn startHourColumn = new DataGridViewComboBoxColumn();
        startHourColumn.HeaderText = "Start Hour";
        startHourColumn.DataSource = Hours;
        startHourColumn.ValueType = typeof(int);
        base.Columns.Add(startHourColumn);
    }

你可以看到我在BeginInit()事件中生成列,因为我发现如果我尝试直接从构造函数中执行它,那么列在运行时会被复制。

当我尝试实际编译并运行程序时,设计器创建此代码(这来自我的Form.Designer):

            // 
        // dataGridViewComboBoxColumn16
        // 
        this.dataGridViewComboBoxColumn16.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
        this.dataGridViewComboBoxColumn16.DataSource = new int[] {
    0,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12,
    13,
    14,
    15,
    16,
    17,
    18,
    19,
    20,
    21,
    22,
    23,
    24};
        dataGridViewCellStyle8.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
        this.dataGridViewComboBoxColumn16.DefaultCellStyle = dataGridViewCellStyle8;
        this.dataGridViewComboBoxColumn16.HeaderText = "Start Hour";
        this.dataGridViewComboBoxColumn16.Items.AddRange(new object[] {
        0,
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        10,
        11,
        12,
        13,
        14,
        15,
        16,
        17,
        18,
        19,
        20,
        21,
        22,
        23,
        24});
        this.dataGridViewComboBoxColumn16.Name = "dataGridViewComboBoxColumn16";
        this.dataGridViewComboBoxColumn16.Width = 61;

您可以看到它已将DataSource设置为小时数组,但随后它会尝试添加一系列值。这会导致异常:

  

其他信息:设置DataSource属性时,无法修改项集合。

我尽职尽责地进入设计师并删除此代码。重新运行并编译,直到我对我的控件或项目进行更改。

任何人都知道发生了什么,以及如何避免这种情况?

0 个答案:

没有答案