【问题标题】:How to set selected index on listbox selection如何在列表框选择上设置选定索引
【发布时间】:2013-09-19 02:38:40
【问题描述】:

我以前做过这个并且完全可以使用,但我不记得是怎么做的

我的项目类后面有 3 个属性

namespace Budgeting_Program
{    
    [Serializable]
    public class Item
    {
        public string Name { get; set; }
        public double Price { get; set; }
        public string @URL { get; set; }

        public Item(string Name, string Price, string @URL)
        {
            this.Name = Name;
            this.Price = Convert.ToDouble(Price);
            this.@URL = @URL;
        }

        public override string ToString()
        {
            return this.Name;
       }
    }
}

现在在我的编辑窗口中

public Edit(List<Item> i, int index)
{
    InitializeComponent();
    itemList = i;
    updateItemList();    
    itemListBox.SetSelected(index, true);                               
}

我希望文本框反映所选索引后面的项目数据。这怎么可能。我记得以前做过,只是不记得我用了什么方法。

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    将 selectedindexchanged 事件添加到列表框中,然后您可以将 selectedItem 转换为 Item,现在您可以访问属性并设置文本框的文本字段

    private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
       Item item = (Item)listBox1.SelectedItem;
       txtName.Text = item.Name;
       txtPrice.Text = item.Price;
       txtUrl.Text = item.Url;
    }
    

    如果您需要更新列表框中的项目,您最好在ListBox Item 上实现INotifyPropertyChanged

    检查这个codeproject article

    【讨论】:

    • 这会正确保存吗?意味着编辑的项目会被处理吗?
    【解决方案2】:
     Item found = itemList.Find(x => x.Name == (string)itemListBox.SelectedItem);
            if (found != null)
            {
                nameText.Text = found.Name;
                priceText.Text = Convert.ToString(found.Price);
                urlText.Text = found.URL;
            }
    

    接近最后一个答案

    【讨论】:

      【解决方案3】:

      您可以使用SelectedItem

      var selection = itemListBox.SelectedItem as Item;
      if (selection != null)
      {
         textboxName.Text = selection.Name;
         textboxPrice.Text = selection.Price;
         textboxUrl.Text = selection.Url;
      }
      

      【讨论】:

      • 这会保存在列表中吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 2012-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      相关资源
      最近更新 更多