如何在标签中显示List <object>值

时间:2019-04-08 10:35:02

标签: c#

我正在尝试在标签文本中显示List<object>的值。我创建了一个列表框,在其中加载了List<Object>的值。现在,我希望标签在列表框中单击时显示List<object>的选定值。

我尝试使用label1.Text = frm.CityName.ToString(); 但返回错误

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());
}

3 个答案:

答案 0 :(得分:1)

如果您的CityNameList<string>,则可以像执行string.Join()一样

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

(OR)您是否正在尝试从List<ForecastForm>()获得它?在这种情况下,请像下面一样使用相同的string.Join()。导入using System.Linq

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

答案 1 :(得分:1)

  

当我单击“列表”框中的元素时,它应该在标签中显示列表的所有元素

您的实际数据在列表框lstCityNames中,因此将该列表框中的项目转换为字符串,并使用string.Join可以显示所有Items,并用逗号(,)分隔字符串在“标签”控件中。

所以请尝试以下

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

答案 2 :(得分:0)

Hie @Calculus学生欢迎使用stackoverflow

尝试一下
确保将代码添加到selectedIndexChanged事件或按钮Click事件中

PutYouLabelNameHere.Text = lstCityNames.SelectedItem.ToString