DataGridViewRow.Tag在TabControl中为null。这是错误吗?

问题描述 投票:0回答:1

我有1个TabControl,这个TabControl有2个Tab,分别是TabPage1和TabPage2。

[TabPage1具有DataGridView1,TabPage2具有DataGridView2。

从数据库加载数据时,我使用DataGridViewRow.Tag属性保存对象。

问题是TabPage1中只有DataGridView1将对象保存到Tag,而TabPage2中不是DataGridView2。

我尝试先加载GridViewTab2的数据,然后再加载GridViewTab1的数据,但没有任何变化。

我找到了一种解决方法:我在加载DataGridView2的数据之前更改了TabControl.SelectedIndex = 1。它工作正常。您可以在我的屏幕截图中看到它。

但是我想知道为什么吗?对不起,我的英语。

        //dataGridView1 in tabControl1.TabPages[0]
        dataGridView1.DataSource = DataProvider.GetPersons();
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            Person p = new Person();
            p.name = row.Cells["name"].Value.ToString();
            p.old = (int)row.Cells["old"].Value;
            p.address = row.Cells["address"].Value.ToString();
            row.Tag = p;    //Add person object to current row.tag
        }

        //If not have row BELOW (*), dataGridView2 row.tag will be null.
        tabControl1.SelectedIndex = 1;  //(*)

        //So I want tabControl1.SelectedTab is the first tab, then I use row below to do that.
        tabControl1.SelectedIndex = 0;

        //dataGridView2 in tabControl1.TabPages[1]
        dataGridView2.DataSource = DataProvider.GetBooks();
        foreach (DataGridViewRow row in dataGridView2.Rows)
        {
            Book b = new Book();
            b.name = row.Cells["name"].Value.ToString();
            b.author = row.Cells["author"].Value.ToString();
            b.price = (int)row.Cells["price"].Value;
            row.Tag = b;    //Add book object to current row.tag
        }

我的代码:“我的代码”

c# winforms
1个回答
0
投票

如评论中所述,您已经通过此行将DataGridView绑定到(大概)一个Person对象列表:

dataGridView1.DataSource = DataProvider.GetPersons();

您可以根据需要从DGV中的选定行中检索数据绑定项。这是一个快速的“星期五晚上,该走了”,复制并粘贴VB.NET示例,但转换为C#应该不容易:

Dim selected As Person = DirectCast(dgvFavorites.SelectedRows(0).DataBoundItem, FavoriteDTO)
© www.soinside.com 2019 - 2024. All rights reserved.