Click here to Skip to main content
15,889,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two list boxes that are populated by a database. When an item in the first ListBox is selected it populates the second ListBox with values related to that item.

The problem I have is if another item is selected in the first ListBox the first item that was selected duplicates the populated item in the second ListBox.

Sorry unable to show an example.

What I have tried:

C#
private void Area_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Area.SelectedItems.Count < 1)
            {
                AreaPostCode.Items.Clear();
                AreasSelected.Clear();
                return;
            }
            AreasSelected.Text = "";
            foreach (object area in Area.SelectedItems)
            {
                AreasSelected.Text += (AreasSelected.Text == "" ? "" : ", ") + area.ToString();
            }

            DataView view = new DataView();
            DataTable dt = new DataTable();
            //SqlDataAdapter adpt = new SqlDataAdapter("SELECT PostCode,Town FROM tblAllPostCodes WHERE Town IN(" + string.Join(",", Area.SelectedItems.Cast<string>().Select(si => "'" + si.ToString() + "'").ToArray()) + ")", sqlConTwo);
            SqlDataAdapter adpt = new SqlDataAdapter("SELECT DISTINCT SUBSTRING(PostCode, 0, 5) AS PostCode, Town FROM tblAllPostCodes WHERE Town IN(" + string.Join(",", Area.SelectedItems.Cast<string>().Select(si => "'" + si.ToString() + "'").ToArray()) + ")", sqlConTwo);

            adpt.Fill(dt);

            foreach (DataRow dr in dt.Rows)
            {
                AreaPostCode.Items.Add(dr["PostCode"].ToString());
            }
         

        }
Posted
Updated 6-Mar-20 11:44am
v2
Comments
Richard MacCutchan 6-Mar-20 4:33am    
You need to clear the AreaPostCode list before adding more items.

Don't do it like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
 
Share this answer
 
Comments
Member 12876243 6-Mar-20 4:56am    
At this stage no need to backup frequently. I have a backup of the database. I can change to parameterized no problem.
OriginalGriff 6-Mar-20 5:04am    
Then do so, throughout your whole app as a priority.
As to the above the refinement of the SQL is the best solution, but outside of better SQL, you could utilize the system.data objects to make the output distinct or a linq based solution. As to the above SQL refinement is the best solution this is always a last last solution.

As well as the code you could use linq with the datarows and utilize the Distinct method.

LINQ to DataSet - ADO.NET | Microsoft Docs[^]

Enumerable.Distinct Method (System.Linq) | Microsoft Docs[^]


DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("name", typeof(string)));

            List<string> names = new List<string>();

            names.Add("Peter");
            names.Add("Peter");
            names.Add("Paul");
            names.Add("Paul");
            names.Add("Matthew");
            names.Add("John");
            names.Add("Rodney");
            names.Add("Derrick");
            names.Add("Albert");
            names.Add("Denzel");

            foreach(string s in names)
            {
                DataRow dr = dt.NewRow();
                dr["name"] = s;
                dt.Rows.Add(dr);
            }
            DataView view = new DataView(dt);
            DataTable distinctValues = view.ToTable(true, "name");


DT =

Peter
Peter
Paul
Paul
Matthew
John
Rodney
Derrick
Albert
Denzel



distinct values=

Peter
Paul
Matthew
John
Rodney
Derrick
Albert
Denzel
 
Share this answer
 
C#
SqlDataAdapter adpt = new SqlDataAdapter("SELECT DISTINCT SUBSTRING(PostCode, 0, 5) AS PostCode, Town FROM tblAllPostCodes WHERE Town IN(" + string.Join(",", Area.SelectedItems.Cast<string>().Select(si => "'" + si.ToString() + "'").ToArray()) + ")", sqlConTwo);

Not necessary a solution to your question, but another problem you have.
Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
How can I explain SQL injection without technical jargon? - Information Security Stack Exchange[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900