【问题标题】:Controls created on one thread cannot be parented to a control on a different thread - Adding DataGridView to TabPage to TabControl在一个线程上创建的控件不能作为另一个线程上的控件的父级 - 将 DataGridView 添加到 TabPage 到 TabControl
【发布时间】:2014-10-11 08:17:44
【问题描述】:

我正在使用 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());
        }

    }

【问题讨论】:

  • 你是从新线程调用这个函数吗?
  • 这是从非 ui 线程调用的。我在想我可能需要methodinvoke?
  • 是的。在父窗体上调用调用
  • 我说的游戏比我能做的更好。你会碰巧有一个关于如何做到这一点的stackoverflow参考吗?我一直在尽我最大的努力实现它,但在 atm 中惨遭失败。

标签: c# winforms datagridview


【解决方案1】:

您需要使用 Invoke 方法。

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

【讨论】:

    猜你喜欢
    • 2013-06-27
    • 2013-01-22
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    相关资源
    最近更新 更多