3

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());                   
            }
NOGRP90
  • 49
  • 2
  • 10
  • why an additional reader? why not the same datatable? – sujith karivelil May 05 '16 at 17:53
  • 1
    I'd use the database to do that for you. Just write a suitable select distinct query for it. You could do it in code using LINQ, but there's no point in this example. e.g. `select distinct Owner from PPAPdatabase where Owner is not null` – ManoDestra May 05 '16 at 17:54
  • Clear the ComboBox first near the top of your method using `comboBox_Owner.Items.Clear()`, then amend your SQL to be `select distinct Owner from PPAPdatabase where Owner is not null`. And you only need to fill the datasource once, you don't really require to do the reader as well. Use either the reader or the datasource method. Job done :) – ManoDestra May 05 '16 at 18:26

2 Answers2

3

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.

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
2

you can do this way

while (reader.Read())
{
    if (!comboBox_Owner.Items.Contains(reader["Owner"].ToString()))
        comboBox_Owner.Items.Add(reader["Owner"].ToString());                  
}
Mostafiz
  • 7,243
  • 3
  • 28
  • 42