Datagridview, Only show unique values were Duplica

2019-03-01 12:31发布

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 programming this I found that inside the loop I need to check for duplicated values and count them and if a new value appears display the value and send a mail, I do have the code for the mail via smtp, but I need the duplicate values to be counted and eliminated only leaving the original cell and updating the rest, Can that be possible, this is the code that’s connected to the grid and the data generation I need serious help with this one, because I haven’t found the correct code on the web to do this job efficiently.

  try
            {

                e.Result = "";

                //int count1 = 0;
                int val = 6000;

                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn("ComputerName", typeof(String)));          //0
                dt.Columns.Add(new DataColumn("IP", typeof(String)));            //1
                dt.Columns.Add(new DataColumn("MAC", typeof(String)));       //2
                dt.Columns.Add(new DataColumn("Descubierto", typeof(String)));  

                for (int a = 1; a <= val; a++)


                {


                    counter.Text = Convert.ToString(a);
                    if (txtWorkGroupName.Text == "") return;

                    //DataTable dt = new DataTable();
                    //dt.Clear();


                        //3
                    //int i = 0;


                    try
                    {
                        // Datos del grupo WinNT://&&&&(Nombre del grupo de trabajo)
                        DirectoryEntry DomainEntry = new DirectoryEntry("WinNT://" + txtWorkGroupName.Text + "");
                        DomainEntry.Children.SchemaFilter.Add("Computer");



                        ///*************************************************
                        /// Interacting with the pcs in the domain
                        ///*************************************************

                        foreach (DirectoryEntry machine in DomainEntry.Children)
                        {

                            string strMachineName = machine.Name;
                            string strMACAddress = "";
                            IPAddress IPAddress;
                            DateTime discovered;

                            try
                            {
                                IPAddress = getIPByName(machine.Name);

                            }
                            catch
                            {
                                continue;
                            }//try/catch

                            ///*************************************************
                            /// Get Mac
                            ///*************************************************
                            strMACAddress = getMACAddress(IPAddress);

                             ///*************************************************
                            /// discovered time
                            ///*************************************************
                            discovered = DateTime.Now;


                            ///*************************************************
                            /// Add the data to the datagridview
                            ///*************************************************

                            DataRow dr = dt.NewRow();


                            dr[0] = machine.Name;
                            dr[1] = IPAddress;
                            dr[2] = strMACAddress;
                            dr[3] = Convert.ToString(discovered);
                            dt.Rows.Add(dr);



                            dgvComputers1.DataSource = dt;



                            dgvComputers1.Refresh();

                   ///Using Unique doesent work, this was one of the solutions found
                            //dt.Columns(machine.Name).Unique = true;
                            //dt.Columns(IPAddress).Unique = true;
                            //dt.Columns(strMACAddress).Unique = true;



                        }//foreach loop


                       // DataView dv = new DataView();

                       // dv = dt;

                        Thread.Sleep(2000);

                        //dt = ((DataView)this.dgvComputers1.DataSource).Table;
                        //dt.WriteXml(@"testermac.xml");




                    }//try/catch

                    catch (Exception ex)
                    {
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }


                    if (backgroundWorker2.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                }

            }
            catch (NullReferenceException ex)
            {
                MessageBox.Show("error:" + ex);
                //tbmessage.Text += "se ha producido un error: " + ex + Environment.NewLine;
                //tbmessage.SelectionStart = tbmessage.Text.Length;
                //tbmessage.ScrollToCaret();
            }
            catch (NoNullAllowedException ex)
            {
                MessageBox.Show("error:" + ex);
            }
            catch (AccessViolationException ex)
            {
                MessageBox.Show("error:" + ex);
            }


        }

1条回答
萌系小妹纸
2楼-- · 2019-03-01 13:09

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();
        } 
    }
查看更多
登录 后发表回答