【问题标题】:Sharing a DataTable across multiple forms in winforms在winforms中跨多个表单共享一个DataTable
【发布时间】:2010-10-30 14:19:21
【问题描述】:

我正在尝试编写一个简单的 Compact Framework winforms 应用程序。主窗体有一个绑定到 DataTable 的 DataGrid(包含来自 xml 文件的数据)。我想调出另一个显示当前记录详细信息的表单。我有类似下面的代码作为详细表单的构造函数。

public DetailsForm(DataTable dtLandlords, int Index) //the constructor
{
  InitializeComponent();
  lLandlordCode.DataBindings.Add("Text", dtLandlords, "LandlordID");
  .......
}

我正在使用以下代码调用构造函数

    Form frm = new LandlordDetailsForm(dtLandlords, dataGrid1.CurrentRowIndex);
    frm.Show();

如何让它显示当前记录(在索引中指定 - 当前未使用),而不仅仅是第一条记录。还是有更好的方法让我这样做?

【问题讨论】:

    标签: winforms data-binding compact-framework datatable


    【解决方案1】:

    数据绑定“绑定”到提供的“视图”,目前您正在绑定到 DataTable 而不设置默认视图(因此它将默认为完整的表)。例如。 dtLandlords.DefaultView.RowFilter = "LandlordID = TheIdYouWant";

    另一种方法是将 DataGrid/GridView 本身添加到 DataBingings 中,这将提供一个包含当前选定项目的默认视图。

    编辑:添加绑定到 DataGridView 的示例

    这方面的一个例子是: 首先创建一个带有 TextBox 和 DataGridView(默认名称)的表单。然后把这段代码放到表单的构造函数中。

    DataTable dt = new DataTable();
    dt.Columns.Add("Col1");
    dt.Columns.Add("Col2");
    DataRow dr;
    dr = dt.NewRow();
    dr[0] = "C1R1";
    dr[1] = "C2R1";
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr[0] = "C1R2";
    dr[1] = "C2R2";
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr[0] = "C1R3";
    dr[1] = "C2R3";
    dt.Rows.Add(dr);
    
    this.dataGridView1.DataSource = dt;
    this.textBox1.DataBindings.Add("Text", dataGridView1.DataSource, "Col1");
    

    然后运行,并选择 GridView 中的项目,TextBox 应该会自动更新所选的详细信息。注意:我在这里使用了 DataGridView,我认为它也适用于 DataGrids(我认为您正在使用)

    【讨论】:

    • 您的第一个建议有效,谢谢。不过,我想了解更多关于将 DataGrid 添加到 DataBindings 的第二条建议
    • 我编辑了主要答案,并举例说明了如何做到这一点。如果这是公认的答案,您可以将其标记为这样吗?我相信通过单击答案评分下的勾号,干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    相关资源
    最近更新 更多