I binded data to a combobox using a dataset.

companycb.DisplayMember = "company";
            companycb.ValueMember = "visitorVisitID";
            companycb.DataSource = ds.Tables["tblVisitorVisit"];

I need to remove the duplicate values from the combobox. Is there any other way instead of doing it using an SQL Distinct query?

Recommended Answers

All 2 Replies

You could store them in an array, and use the "distinct()" method.

I'm not sure if there's a more direct way to do it. Perhaps someone else here might know.

commented: thanks for the idea +1

Look at this code, it removes the duplications:

public partial class Form1 : Form
    {
        DataSet ds;
        public Form1()
        {
            InitializeComponent();
            CreatingDS();            
        }

        private void CreatingDS()
        {
            ds = new DataSet();
            DataTable table = new DataTable("MyTable");
            table.Columns.Add("id", typeof(int));
            table.Columns.Add("name", typeof(string));

            string[] names = { "A", "B", "C", "A", "B" };
            DataRow dr;
            for (int i = 0; i < names.Length; i++)
            {
                dr = table.NewRow();
                dr["id"] = i + 1;
                dr["name"] = names[i];
                table.Rows.Add(dr);
            }
            ds.Tables.Add(table);
            table = RemoveDuplicateRows(table, "name");

            comboBox1.DataSource = ds.Tables["MyTable"];
            comboBox1.DisplayMember = "name";
            comboBox1.ValueMember = "id";
        }

        public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
        {
            Hashtable hTable = new Hashtable();
            ArrayList duplicateList = new ArrayList();

            foreach (DataRow drow in dTable.Rows)
            {
                if (hTable.Contains(drow[colName]))
                    duplicateList.Add(drow);
                else
                    hTable.Add(drow[colName], string.Empty);
            }

            foreach (DataRow dRow in duplicateList)
                dTable.Rows.Remove(dRow);

            return dTable;
        }
    }

hope it helps,
Mitja

commented: thanks for combobox removal of dups! +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.