如何正确获取datagridview

时间:2015-04-04 11:47:34

标签: c# winforms

在我的WinForms应用程序中,我有三个选项卡,每个选项卡中都有一个gatagridview。 如果我点击一个btn来显示tab1 datagridview中的记录,它会填充但是如果我转到tab2并按一个按钮显示不同的记录,它首先会显示正确的记录,然后显示我的相同内容如果单击其他按钮,则在tab1或tab3中记录。

然后它会从tab1,tab2和tab3填充相同的记录。

我怎样才能解决这个问题,还是我宣布了一个全局数据表dt变量?

1 个答案:

答案 0 :(得分:1)

如果您希望3 DGVs拥有自己的记录指针,则不得直接使用DataTable作为DataSource。而是为每个人使用中间BindingSource

    // assume a few DataGridViews..: 
    DataGridView DGV1 = new DataGridView();
    DataGridView DGV2 = new DataGridView();
    DataGridView DGV3 = new DataGridView();

    // and a common DataTable:
    DataTable DT = new DataTable();
    //..

    // we need a separate BindingSource for each DGV:
    BindingSource BS1 = new BindingSource();
    BindingSource BS2 = new BindingSource();
    BindingSource BS3 = new BindingSource();

    // each is bound to the DataTable
    BS1.DataSource = DT;
    BS2.DataSource = DT;
    BS3.DataSource = DT;

    // now we set them to be the DatSource of the DGVs:
    DGV1.DataSource = BS1;
    DGV2.DataSource = BS2;
    DGV3.DataSource = BS3;

    // now we can set the record pointers separately:
    BS1.Position = 3;        
    BS2.Position = 0;        
    BS3.Position = BS3.Count - 1;   

    // or set filters:
    BS2.Filter = "someCondition";  

    // or set sorts:
    BS3.Filter = "someSort";