举个例子,如何让listbox显示学生姓名,但是当用户点击某一项时候同时能够知道这学生的id,主要是为了区别重名的学生。
在线等待...

解决方案 »

  1.   

    用一个ToolTip实现吧.
    在ListBox的SelectedChanged事件中触发ToolTip的显示.this.yourToolTip.Active = true;
    this.yourToolTip.SetToolTip(this.yourListBox,"选中的学生ID");
      

  2.   

    我没说明白...
    我是说把学生姓名加倒listbox以后,假如有两个叫张三的
    ,都显示在了里面,怎么样才能知道用户点的那个张三的id呢?
      

  3.   

    ListBox.Items.Add(Object )'s parameter is Object type, So you can define a struct of your own, and override ToString() method, See this.class StudentInfo
    {
        public string Name;
        public string ID;
        public override string ToString()
        {
            return Name;
        }
    }Add to listBox:   StudentInfo student = new StudentInfo();
       student.Name = "Jeffrey";
       student.ID = 32;
       listBox1.Items.Add(student);Read list this;   StudentInfo student = (StudentInfo) listBox1.SelectedItem;
       MessageBox.Show(student.Name + " " + student.ID);This code is ran successfully on Visual Studio.NET 2005.
      

  4.   

    using System.Text;
    using System.Windows.Forms;class Items
    {
      string DisplayMember;
      object ValueMember;  public Items(string Text, object Value )
      {
        DisplayMember = Text;
        ValueMember   = Value;
      }  public object Value
      {
        get { return ValueMember; }
      }  public override string ToString()
      {
        return DisplayMember;
      }
    }class Test : Form
    {
      ListBox lbx;  Test()
      {
        Text               = "选择一些项目, 然后单击窗口下半部";
        lbx                = new ListBox();
        lbx.Parent         = this;
        lbx.Width          = 243;
        lbx.Height         = 67;
        lbx.IntegralHeight = false;
        lbx.ColumnWidth    = 60;
        lbx.MultiColumn    = true;
        lbx.BackColor      = BackColor;
        lbx.BorderStyle    = BorderStyle.FixedSingle;
        lbx.SelectionMode  = SelectionMode.MultiSimple;
        string [] ID   = { "0001", "0002", "0003", "0004", "0005", "0007", "0008" };
        string [] Name = { "张三", "李四", "王五", "张三", "钱六", "张三", "钱六" };
        for (int i = 0; i < ID.Length; i++)
        {
          lbx.Items.Add(new Items(Name[i], ID[i]));
        }
      }  protected override void OnClick(System.EventArgs e)
      {
        StringBuilder sb = new StringBuilder();
        foreach (Items o in lbx.SelectedItems)
        {
          sb.AppendFormat("{0}: [{1}]\n", o, o.Value);
        }
        MessageBox.Show(sb.ToString());
      }  static void Main()
      {
        Application.Run(new Test());
      }
    }