DataGridView:更改数据源后保留选择? [英] DataGridView: Keep selections after datasource is changed?

查看:21
本文介绍了DataGridView:更改数据源后保留选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DataSource 改变后,有没有办法让 DataGridView 的选中单元格保持选中状态?

Is there a way to keep the selected cells of a DataGridView selected after the DataSource is changed?

推荐答案

您可以根据特定于您的需要的条件匹配应选择的内容,只需将单元格或行的 Select 属性设置为 true/false,具体取决于您的需求匹配.这是一个简单的示例,您可以将其放入新创建的 winforms 项目中,以说明这一点.为了让这个例子工作,确保你设置了 DataGridView 的 SelectionMode = FullRowSelect.如果您想保留/重新应用单元格选择,则方法类似.注意:您也可以只保留选定行索引的列表,但这在加载另一个数据源时通常没有意义,因为通常不太可能实际行与其在数据中的物理位置之间存在任何对应关系.

You can match what should be selected based on criteria specific to your needs and just set the Select property of either the cell or row to true/false depending on your matching. Here's a simple example you can drop in a newly created winforms project that will illustrate the point. For this example to work make sure you set the DataGridView's SelectionMode = FullRowSelect. If you want to retain/reapply cell selections the approach would be similar. Note : you could also just retain a list of selected row indexes but this typically wouldn't make sense when loading another data source as it's usually unliklely that there would be any correspondence between the actual rows and their physical position in the data.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace DataGridViewRetainSelection
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private readonly List<Person> currentPeople = new List<Person>();
        private bool dummyToggle = true;

        private void Form1_Load(object sender, EventArgs e)
        {
            SwitchDataSource(); // will just new up the datasource
        }

        private void ButtonSwitchDataSourceClick(object sender, EventArgs e)
        {
            SwitchDataSource();
        }

        private void SwitchDataSource()
        {
            var selectedPeople = (from DataGridViewRow row in dataGridViewPeople.Rows where row.Selected select currentPeople[row.Index]).ToList();

            peopleBindingSource.DataSource = null;

            currentPeople.Clear();
            if (dummyToggle)
            {
                currentPeople.Add(new Person { Name = "Joel Spolsky" });
                currentPeople.Add(new Person { Name = "Jeff Atwood" });
                currentPeople.Add(new Person { Name = "Jarrod Dixon" });
                currentPeople.Add(new Person { Name = "Geoff Dalgas" });
                currentPeople.Add(new Person { Name = "Brent Ozar" });
            }
            else
            {
                currentPeople.Add(new Person { Name = "Joel Spolsky" });
                currentPeople.Add(new Person { Name = "Jeff Atwood" });
                currentPeople.Add(new Person { Name = "Brent Ozar" });
            }

            dummyToggle = !dummyToggle;

            peopleBindingSource.DataSource = currentPeople;

            foreach (var person in selectedPeople)
            {
                foreach (DataGridViewRow row in dataGridViewPeople.Rows)
                {
                    if (string.Equals(row.Cells[0].Value, person.Name))
                    {
                        row.Selected = true;
                    }
                }
            }
        }
    }

    public sealed class Person
    {
        public string Name { get; set; }
    }

}

要为选定的单元格实现相同的功能,请执行以下操作.如果其他人需要它,我将保留以前的代码.注意:我只是在这里敲出一个匿名类型,您可能需要根据成员字段、属性等做一些更复杂的事情.但是设置所选单元格的一般原则已正确说明并且可以我希望可以轻松测试和调试以供理解.

To implement the same functionality for selected cells do something like the following. I'm leaving the previous code should anyone else need it. Note: I'm just banging out an anonymous type here, you're probably going to need to do something a little more sophisticated depending on member fields, properties, etc. but the general principal of setting the selected cells is illustrated properly and can easily be tested and debugged for understanding I hope.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace DataGridViewRetainSelection
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private readonly List<Person> currentPeople = new List<Person>();
        private bool dummyToggle = true;

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridViewPeople.SelectionMode = DataGridViewSelectionMode.CellSelect;
            SwitchDataSource(); // will just new up the datasource
        }

        private void ButtonSwitchDataSourceClick(object sender, EventArgs e)
        {
            SwitchDataSource();
        }

        private void SwitchDataSource()
        {
            var selectedPeopleAndCells = (from DataGridViewCell cell in dataGridViewPeople.SelectedCells where cell.Selected select new { Person = currentPeople[cell.RowIndex], Cell = cell }).ToList();

            peopleBindingSource.DataSource = null;

            currentPeople.Clear();
            if (dummyToggle)
            {
                currentPeople.Add(new Person { Name = "Joel Spolsky", Id = 0 });
                currentPeople.Add(new Person { Name = "Jeff Atwood", Id = 1 });
                currentPeople.Add(new Person { Name = "Jarrod Dixon", Id = 2 });
                currentPeople.Add(new Person { Name = "Geoff Dalgas", Id = 3 });
                currentPeople.Add(new Person { Name = "Brent Ozar", Id = 4 });
            }
            else
            {
                currentPeople.Add(new Person { Name = "Joel Spolsky", Id = 0 });
                currentPeople.Add(new Person { Name = "Jeff Atwood", Id = 1 });
                currentPeople.Add(new Person { Name = "Brent Ozar", Id = 4 });
            }

            dummyToggle = !dummyToggle;

            peopleBindingSource.DataSource = currentPeople;

            foreach (var personAndCell in selectedPeopleAndCells)
            {
                foreach (DataGridViewRow row in dataGridViewPeople.Rows)
                {
                    if (string.Equals(row.Cells[0].Value, personAndCell.Person.Id))
                    {
                        row.Cells[personAndCell.Cell.ColumnIndex].Selected = true;
                    }
                }
            }
        }
    }

    public sealed class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

}

这篇关于DataGridView:更改数据源后保留选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆