列表框更改后如何显示更多信息?

时间:2014-10-19 19:55:19

标签: c# winforms events

我正在尝试制作一个C#程序来显示相册信息。当选择列表框中的项目时,如何在右侧的字段中显示信息?

GUI:

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Assignment_2_S2_2014
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void saveChangesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Album information is automatically saved, if none are showing try LOAD option.");
        }

        private void loadAlbumsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {

                lbxAlbums.Items.Clear();
                foreach (var line in File.ReadLines("Albums.dat"))
                {
                    string[] tokens = line.Split(',');
                    lbxAlbums.Items.Add(tokens[0] + " - " + tokens[1]);
                }
                MessageBox.Show("Load Complete!");
            }
            catch (Exception)
            {

                MessageBox.Show("No Albums Found. Try Adding Some First!");
            }
        }

        private void printSelectedToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            PrintDialog dlg = new PrintDialog();
            dlg.ShowDialog();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            NewAlbum frm = new NewAlbum();

            frm.Show();

        }

        private void lbxAlbums_SelectedIndexChanged(object sender, EventArgs e)
        {
            string a = lbxAlbums.SelectedIndex.ToString();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

SelectedIndexChanged事件处理程序中,您需要获取所选项目并通过拆分来从中提取值:

private void lbxAlbums_SelectedIndexChanged(object sender, EventArgs e)
{
    string title, artist = "";

    title = lbxAlbums.SelectedItem.ToString().Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries)[0];
    artist = lbxAlbums.SelectedItem.ToString().Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries)[1];

    //now you can use them to assign those labels
}