Domanda

I want to get the names associated with the states i select in my program. Below is the code that i currently have. My database has multiple locations within a state that have different contacts. I just want to select a state and acquire everyone under that state. Thanks for the help!

con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Database\\LocNo.accdb");
con.Open();

foreach (Object c in checkedListBox2.CheckedItems)
{
    if (checkedListBox2.GetItemCheckState(checkedListBox2.Items.IndexOf(c)) == CheckState.Checked)
    {
        str1 += c.ToString() + ","; 
        flag = 1;
    }
}

i = 0;
allSelectedtypestring = "";
allSelected = str1.Split(',');


while (allSelected.Length - 1 > i)
{
    str = "select c1 from table where state ='" + allSelected[i++] + "'";
    cmd = new OleDbCommand(str, con);
    dr = cmd.ExecuteReader();

    dr.Read();
    allSelectedtypestring += dr.GetString(11);
}

label30.Text = Convert.ToString(allSelectedtypestring);
con.Close();
È stato utile?

Soluzione

You can use the following code to retrieve the contacts:

var states = new List<string>();
foreach (Object c in checkedListBox2.CheckedItems)
{
    states.Add(c.ToString()); 
    flag = 1;  // Can also be substituted by states.Count > 0
}

using(var con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Database\\LocNo.accdb"))
{
    con.Open();
    using(var cmd = con.CreateCommand())
    {
        var paramIndex = 0;
        var paramClause = new System.Text.StringBuilder(100);
        foreach(var state in states)
        {
            if (paramClause.Length > 0)
                paramClause.Append(", ");
            paramClause.Append("?");
            var paramName = "State" + (paramIndex++).ToString();
            cmd.Parameters.AddWithValue(paramName, state);
        }
        var paramsClause = string.Join(", ", cmd.Parameters.
        cmd.CommandText = "select distinct c1 from table where state IN (" + paramsClause.ToString() + ")";
        using(var rdr = cmd.ExecuteReader())
        {
            var contacts = new List<string>();
            while(rdr.Read())
            {
                contacts.Add(rdr.GetString(0);
            }
            label30.Text = string.Join(", ", contacts);
        }
    }        
}

Please note that I've made the following changes:

  • Added using statements to reliably dispose the connection, command and reader.
  • Used a List<string> as a more convenient way to collect the selected states.
  • Added DISTINCT to the SELECT in order to filter duplicate entries.
  • Used a parameter in the command text in order to avoid SQL injection attacks. Though this way to use a parameter with an IN clause works for SQL Server, I haven't checked whether it also works for an Access database. Let me know in the comments if it doesn't work.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top