首页 > 解决方案 > 如何使用 C# Winforms 从子窗体调用父窗体中的数据表?

问题描述

我尝试使用 ParentForm 类或 Parent 类创建一个实例,但无法获取已在父窗体中创建的数据表。请在我试图从我的子表单中获取的父表单中找到以下代码示例。

    private void ParentForm_Load(object sender, EventArgs e)
    {
        try
        {
            BLGridsToControls objBL = new BLGridsToControls();
            dgMainGrid.DataSource = objBL.GetCity();
        }
        catch
        {
            throw;
        }

注意:objBL.GetCity 返回一个数据表

标签: c#winforms

解决方案


您可以通过创建一个接受 DataTable 作为参数的构造函数,然后调用该构造函数,将 dataTable 传递给子窗体。例如

var childForm = new ChildForm(dgMainGrid.DataSource);
childForm.ShowDialog();

在 ChildForm 中:

DataTable myDataSource { get; set; }

ChildForm(DataTable myDataTable)
{
     // do something with myDataTable, such as put it into a property for later use, 
     myDataSource = myDataTable;
}

推荐阅读