在一个线程上创建的控件不能作为另一个线程上的控件的父级 - 将DataGridView添加到TabPage到TabControl

时间:2014-10-11 08:17:45

标签: c# winforms datagridview

我在实际上使用DataGridView创建TabPage。 TabPage的显示正确,但它们缺少DataGridView。任何人都能够辨别出为什么DGV没有出现在标签上? LoadDataGridToTab的格式正确。它是从另一个表格调用的。应该?

    public void LoadDataGridToTab(Main main, string category)
    {
        try
        {
            //Set Cell Style
            var dataGridViewCellStyle = new DataGridViewCellStyle
            {
                Alignment = DataGridViewContentAlignment.MiddleLeft,
                BackColor = SystemColors.Control,
                Font = new Font("Microsoft Sans Serif", 8.25F,
                    FontStyle.Regular, GraphicsUnit.Point, 0),
                ForeColor = SystemColors.WindowText,
                SelectionBackColor = SystemColors.Highlight,
                SelectionForeColor = SystemColors.HighlightText,
                WrapMode = DataGridViewTriState.True
            };

            //Make the Grid
            var grid = new DataGridView
            {
                Name = "dgv_" + category,
                Text = category,
                Visible = true,
                Dock = DockStyle.Fill,
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize,
                ColumnHeadersDefaultCellStyle = dataGridViewCellStyle,
                DataSource = Auction.CacheAuctionsDataSet.Tables[category]
            };

            //Binding
            //var source = new BindingSource();
            //source.DataSource = CacheAuctionsDataSet.Tables[category];

            //Made the Tab
            var tmpTabPage = new TabPage(category)
            {
                Name = "tabctrl_" + category,
                Text = category,
                Visible = true
            };

            //Add the Grid to the Tab
            tmpTabPage.Controls.Add(grid);
            tmpTabPage.Refresh();

            //Add the Tab to the Control
            tabctrl_Auctions.Controls.Add(tmpTabPage);
            tabctrl_Auctions.Refresh();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

    }

1 个答案:

答案 0 :(得分:0)

您需要使用Invoke方法。

这里有一个例子https://stackoverflow.com/a/253150/2633161