简体   繁体   中英

C# WinForm - Compare DataReader w/ Listbox Contents and Display the Matches

I am attempting to tackle a project where I am pulling a column of data from an SQL database and comparing the data with values within a listbox. So far, it is finding a comparison, but is only returning one value, even with multiple matches in the listbox.

What am I doing wrong here? Thanks for any help anyone can offer.

    private void btnDoAudit_Click(object sender, EventArgs e)
    {
        string respName = "something";
        SqlDataReader reader = null;

        using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=XXXX;Integrated Security=True;;User Instance=True"))
        {
            using (SqlCommand command = new SqlCommand("SELECT [Responsibility_Name] FROM [tblResponsibility] WHERE [Sensitive_Transaction]='TRUE'", conn))
            {
                conn.Open();

                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    respName = (string)reader["Responsibility_Name"];



                        if (lstResponsibilities.Items.Contains(respName) == true)
                        {
                          txtResults.Text = respName;
                        }

                }
                reader.Close();
                conn.Close();
            }
        }
    }

You're overwriting your txtResults.Text every time you find a match. You can append instead:

txtResults.Text += respName;

Or maybe you'd rather just keep the list of matches in a List and then join them into something more legible. You could put this near the top of your method where you're declaring your other variables:

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

Then instead of setting txtResults.Text, you'd just do:

matches.Add(respName);

And once you're done with the SqlConnection, at the end of your method, you can join them into a nice-looking string:

txtResults.Text = string.Join(", ", matches);

Looks like in your while statement, every time you find a match, you overwrite the previous matches:

txtResults.Text = respName;

Maybe you want to create a comma separated list of them:

txtResults.Text += respName + ", ";

Then trim the last comma afterwards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM