【问题标题】:How to select index in listbox如何在列表框中选择索引
【发布时间】:2012-12-12 08:44:28
【问题描述】:

我在 property grid 中将 string array 显示为 listbox,并带有 type converter,代码如下。
如何选择列表框的索引以初始化第一次加载的程序?我想要 SelectedIndex = 0,首先显示 arrData = "one"。有什么想法吗?

public partial class Form1 : Form
{
    string[] arrData = new string[] { "one", "two", "three" };
    PropertyGrid pGrid = new PropertyGrid();

    public Form1()
    {
        InitializeComponent();

        FirstClass fClass = new FirstClass(arrData);
        pGrid.SelectedObject = fClass;
        pGrid.Dock = DockStyle.Fill;
        this.Controls.Add(pGrid);
    }

    public class FirstClass
    {
        public FirstClass(string[] arrData)
        {
            this.DataSource = arrData;
        }

        [Browsable(true)]
        [DefaultValue("one")]
        [TypeConverter(typeof(SecondClass))]
        public string Counter { get; set; }

        [Browsable(false)]
        public string[] DataSource { get; set; }

    }

    public class SecondClass : StringConverter
    {
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            FirstClass fClass = (FirstClass)context.Instance;
            if (fClass == null || fClass.DataSource == null)
            {
                return new StandardValuesCollection(new string[0]);
            }
            else
            {
                return new StandardValuesCollection(fClass.DataSource);
            }
        }

    }

}

【问题讨论】:

    标签: c# winforms listbox propertygrid typeconverter


    【解决方案1】:

    如果我理解正确,如果您只想将列表框中所选项目的索引设置为 0,则应该像下面的代码一样简单。

    ListBox.SelectedIndex = 0;
    

    有关详细信息,请查看 MSDN 页面。

    http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selectedindex.aspx

    【讨论】:

    • 你是对的ListBox.SelectedIndex = 0;如果使用ListBox控件设置ListBox的索引,但问题是Counter属性使用字符串类型,而不是ListBox。跨度>
    猜你喜欢
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 2018-10-17
    相关资源
    最近更新 更多