将数组值分配给某个变量,数组被填充

本文关键字:数组 变量 填充 分配 | 更新日期: 2023-09-27 17:56:13

ArrayList USStates填充了如图所示的值,但是如果我想在数组中访问这些值,我该怎么做?通过USStates(1)引用不起作用。谁能解释这行代码?

USStates.Add(new USState("Alabama", "AL"));

完整代码:

// Populate the list box using an array as DataSource.
ArrayList USStates = new ArrayList();
USStates.Add(new USState("Alabama", "AL"));
USStates.Add(new USState("Washington", "WA"));
USStates.Add(new USState("West Virginia", "WV"));
USStates.Add(new USState("Wisconsin", "WI"));
USStates.Add(new USState("Wyoming", "WY"));
ListBox1.DataSource = USStates;
// Set the long name as the property to be displayed and the short
// name as the value to be returned when a row is selected.  Here
// these are properties; if we were binding to a database table or
// query these could be column names.
ListBox1.DisplayMember = "LongName";
ListBox1.ValueMember = "ShortName";
public class USState
{
    private string myShortName;
    private string myLongName;
    public USState(string strLongName, string strShortName)
    {
        this.myShortName = strShortName;
        this.myLongName = strLongName;
    }
    public string ShortName
    {
        get
        {
            return myShortName;
        }
    }
    public string LongName
    {
        get
        {
            return myLongName;
        }
    }
}

将数组值分配给某个变量,数组被填充

我建议您使用Generic List来满足性能需求(Boxing unboxing, ...)

List<USState> listToBind = new List<USState> { new USState("Alabama", "AL"), new USState("Washington", "WA") };
ListBox1.DataSource = listToBind ;
ListBox1.DisplayMember = "ShortName";
ListBox1.ValueMember = "LongName"; 

友情链接 : http://msdn.microsoft.com/fr-fr/library/vstudio/6sh2ey19.aspx

这个问题有点令人困惑/不完整,不知何故,如果您的目的只是创建一个查找表并将其绑定到下拉列表,那么您可以这样做。

private static Hashtable LookUpIdTable = null;

然后在您的主函数中或如果您想创建一个单独的类:

            LookUpIdTable.Add("AL", "Alabama");
            LookUpIdTable.Add("AK", "Alaska");
            LookUpIdTable.Add("AS", "American Samoa");
            LookUpIdTable.Add("AZ", "Arizona");
            LookUpIdTable.Add("AR", "Arkansas");
            LookUpIdTable.Add("CA", "California");
            LookUpIdTable.Add("CO", "Colorado");
            LookUpIdTable.Add("CT", "Connecticut");

当您想要绑定时:

        DropDown.DataSource = LookUpIdTable
        DropDown.DataValueField = "Key";
        DropDown.DataTextField = "Value";
        DropDown.DataBind();