Home > Software design >  C# How to eliminate duplicate values from comboBox?
C# How to eliminate duplicate values from comboBox?

Time:08-26

I would like to eliminate duplicates from OleDbDataReader Should be easy but I'm spinning my wheels. Any help would be appreciated!

        private void Database_Load(object sender, EventArgs e)
        {         
            try
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                string query = "select * from PPAPdatabase";
                command.CommandText = query;                

                OleDbDataAdapter da = new OleDbDataAdapter(command);
                dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;

                OleDbDataReader reader = command.ExecuteReader();
                while (reader.Read())
            {
                comboBox_Owner.Items.Add(reader["Owner"].ToString());                   
            }

CodePudding user response:

Refactor your SQL query like this :

select distinct Owner from PPAPdatabase

Instead of

select * from PPAPdatabase

The only column you need in your code is Owner then get that only one column and apply DISTINCT clause to it to get distinct value for that column.

Or replace the following lines :

OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
    comboBox_Owner.Items.Add(reader["Owner"].ToString());                   
}

By this :

var owners = dt.AsEnumerable().Select(row => row["Owner"].ToString()).Distinct();
foreach(var owner in owners)
{
    comboBox_Owner.Items.Add(owner);                   
}

In this solution we're using one SQL Query to your Database and reuse the result to extreact distinct owners.

CodePudding user response:

you can do this way

while (reader.Read())
{
    if (!comboBox_Owner.Items.Contains(reader["Owner"].ToString()))
        comboBox_Owner.Items.Add(reader["Owner"].ToString());                  
}
  • Related