Skip to content
Advertisement

system.linq.enumaerable+<Cast… in combobox C#

I have a SQL query that reads string data from a SQL Express DB (Changing over to Azure). Once the data is retrieved, I read it into an array and then display the contents of the array in a combo-box. i am not receiving any error however, in the combo-box, an extra field is displayed and I cannot fgure out how to prevent this.

I have a class for the array that is created with {get; set;}. Below is the actual code for the main program:

LocationList[] address1 = null;

string sql = @"SELECT Address1 FROM DN";

using (var cmd = new SqlCommand(sql, connectionString))
{
    connectionString.Open();
    using (var sqlReader = cmd.ExecuteReader())
    {
        var list = new List<LocationList>();
        while (sqlReader.Read())
        {
            list.Add(new LocationList { Address1 = sqlReader.GetString(0) });
        }
        address1 = list.Distinct().ToArray();
        sqlReader.Close();
    }
    connectionString.Close();  
}

cbTransferTo.Items.Add(address1.Cast<string>());

enter image description here

Also, every time I click on the drop down, an extra item is added without me having to start and stop the program. It’s not supposed to do this and I can’t find the issue.

What the program needs to do is only display the contents it gets from the SQL database table which is a list of locations.

Your help is much appreciated.

Advertisement

Answer

You’re adding a single item to the combobox, but that single item is the return value from Cast<string>(), which is a sequence. The type doesn’t override ToString(), so you’re getting the name of the type instead.

What I believe you want to do is add all the items to the combobox:

foreach (var location in address1)
{
    cbTransferTo.Add(location.Address1);
}

Note that if you just iterate over the result of Cast<string>(), I’d expect an exception anyway – because address1 is a sequence of LocationList items, not strings. It’s not clear why you’re using LocationList at all though – I suspect it would be simpler just to use a string to start with. Simpler code would be:

string sql = @"SELECT Address1 FROM DN";

List<string> addresses = new List<string>();
using (var cmd = new SqlCommand(sql, connectionString))
{
    connectionString.Open();
    using (var sqlReader = cmd.ExecuteReader())
    {
        while (sqlReader.Read())
        {
            addresses.Add(sqlReader.GetString(0));
        }
    }
    connectionString.Close();  
}

foreach (var address in addresses.Distinct())
{
    cbTransferTo.Add(address);
}

It would be even better to use DISTINCT in your SQL, so that you can get the database to do the de-duping rather than fetching all the data into your program and then de-duping…

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement