Calculus Student
Calculus Student

Reputation: 7

How to display List<Object> values in a Label

I'm trying to display a value of a List<object> in a label text. I have created a List Box, where I have loaded the values of the List<Object>. Now I want the label to display the selected value of the List<object> when it's clicked in the List Box.

I have tried using label1.Text = frm.CityName.ToString(); but it returns an error

public  void WeatherReport_Load(object sender, EventArgs e)
{
    ForecastForm frm = new ForecastForm();
    List<ForecastForm> fWeather = new List<ForecastForm>();
    fWeather.Add(new ForecastForm
    {
        CityName = "Cape Town",
        dateTime = new DateTime(2019, 01, 01),
        MinTemp = 15,
        MaxTemp = 25,
        cPrep = 80,
        cHumid = 60,
        WindSpeed = 154
    });

    foreach (ForecastForm details in fWeather)
    {
        lstCityNames.Items.Add(String.Format(details.CityName));
    }
}

private void lstCityNames_SelectedIndexChanged(object sender, EventArgs e)
{
    wReport.Text = string.Join(",", x.CityName.Select(x => x.CityName).ToList());
}

Upvotes: 1

Views: 2555

Answers (3)

er-sho
er-sho

Reputation: 9771

When i click an element in the List box it should show all the elements of the List in a label

Your actual data is in listbox lstCityNames so cast items in this listbox to string and with string.Join you can display all Itemss with comma (,) separated string in your Label control.

So try below,

private void lstCityNames_SelectedIndexChanged(object sender, EventArgs e)
{
    wReport.Text = string.Join(",", lstCityNames.Items.Cast<String>().ToList());
}

Upvotes: 1

Tendai Mare
Tendai Mare

Reputation: 31

Hie @Calculus Student welcome to stackoverflow

Try this
Make sure to add your code in the selectedIndexChanged event or a button Click event

PutYouLabelNameHere.Text = lstCityNames.SelectedItem.ToString

Upvotes: 0

Rahul
Rahul

Reputation: 77926

If your CityName is a List<string> then you can perform string.Join() like

label1.Text = string.Join(",", frm.CityName);

(OR) are you trying to get it from List<ForecastForm>()? In such case as well use the same string.Join() like below. Import using System.Linq

label1.Text = string.Join(",", frm.CityName.Select(x => x.CityName).ToList());

Upvotes: 1

Related Questions