首页 > 解决方案 > 单击列表框中的姓名时如何显示生日

问题描述

我正在使用visual c#,windows forms app(.net framework)

public partial class Form1 : Form
{
    private Dictionary<string, string> birthdays =
        new Dictionary<string, string>()
        {
            {"Cameron", "4/17/1998"},
            {"Kathryn", "5/7/1997"},
            {"Jason", "1/22/1997"},
            {"Lola", "5/5/1995"},
            {"Wesley", "10/4/1999"}
        };

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (var element in birthdays)
        {
            namesListBox.Items.Add(element.Key);
        }
    }

    private void namesListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        string name = namesListBox.SelectedItems.ToString();
        string birthday = birthdays[name];
        birthdayLabel.Text = birthday;
    }
}
}

标签: c#visual-studio

解决方案


只需要做一个简单的改变。. . .将SelectedItems 更改为 SelectedItem。.. 我正在粘贴namesListBox_SelectedIndexChanged事件的更正代码。

private void namesListBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string name = namesListBox.SelectedItem.ToString();
    string birthday = birthdays[name];
    birthdayLabel.Text = birthday;
}

希望它可以帮助你。. .让我知道您是否还有其他顾虑。.


推荐阅读