Datagridview, Only show unique values were Duplicate Cell Values C# 2005

こ雲淡風輕ζ 提交于 2019-12-02 07:11:15

Instead of adding a new row every time try using DataTable.Select or DataTable.Rows.Find to check for a duplicate. If there is no duplicate add a new new row, if it already exists just update the other columns.

Also you're setting the DataSource on every iteration of the loop, you only need to do this once.

Here is a simple incomplete example that updates the grid every second, you should be able to adapt the logic here for your program.

    public partial class Form1 : Form
    {
        private readonly DataGridView _gridView;
        private readonly DataTable _dataTable;

        public Form1()
        {
            InitializeComponent();

            _dataTable = new DataTable();
            DataColumn computerColumn = new DataColumn("Name");
            _dataTable.Columns.Add(computerColumn);
            _dataTable.Columns.Add(new DataColumn("IP"));
            _dataTable.Columns.Add(new DataColumn("MAC"));
            _dataTable.Columns.Add(new DataColumn("Descubierto"));
            _dataTable.PrimaryKey = new [] { computerColumn };

            _gridView = new DataGridView
                            {
                                Dock = DockStyle.Fill,
                                DataSource = _dataTable
                            };
            Controls.Add(_gridView);

            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = 1000;
            timer.Tick += TimerTick;     
            timer.Start();
        }

        void TimerTick(object sender, EventArgs e)
        {
            DirectoryEntry domainEntry = new DirectoryEntry("WinNT://mydomain"); 
            domainEntry.Children.SchemaFilter.Add("Computer"); 

            _dataTable.BeginLoadData();

            foreach (DirectoryEntry machine in domainEntry.Children) 
            { 
                DataRow row = _dataTable.Rows.Find(machine.Name);

                if(row == null)
                {
                    row = _dataTable.NewRow();
                    row[0] = machine.Name;
                    _dataTable.Rows.Add(row);
                }

                row[3] = DateTime.Now.ToString();
            }

            _dataTable.EndLoadData();
        } 
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!