NOGRP90
NOGRP90

Reputation: 49

C# How to eliminate duplicate values from comboBox?

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());                   
            }

Upvotes: 3

Views: 7294

Answers (2)

CodeNotFound
CodeNotFound

Reputation: 23200

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.

Upvotes: 3

Mostafiz
Mostafiz

Reputation: 7352

you can do this way

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

Upvotes: 2

Related Questions