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

后端 未结 1 368
日久生厌
日久生厌 2021-01-23 14:54

I have some issues to display values but every time it duplicates the values in the datagridview, I’m using Microsoft Visual C# 2005 and framework 2.0.

As I was programm

相关标签:
1条回答
  • 2021-01-23 15:32

    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();
            } 
        }
    
    0 讨论(0)
提交回复
热议问题