ASP.NET 数据绑定到列表控件

<div>

    <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>

    <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

    <asp:CheckBoxList ID="CheckBoxList1" runat="server"></asp:CheckBoxList>

    <asp:RadioButtonList ID="RadioButtonList1" runat="server"></asp:RadioButtonList>

</div>
protected void Page_Load(object sender, EventArgs e)

{

    List<string> fruit = new List<string>();

    fruit.Add("Kiwi");

    fruit.Add("Pear");

    fruit.Add("Mango");

    fruit.Add("Blueberry");

    fruit.Add("Apricot");

    fruit.Add("Banana");

    fruit.Add("Peach");

    fruit.Add("Plum");



    ListBox1.DataSource = fruit;

    DropDownList1.DataSource = fruit;

    CheckBoxList1.DataSource = fruit;

    RadioButtonList1.DataSource = fruit;



    this.DataBind();

}

 

ASP.NET 数据绑定到列表控件

进阶:数据绑定到字典集合

protected void Page_Load(Object sender, EventArgs e)

{

    if (!this.IsPostBack)

    {

        // Use integers to index each item. Each item is a string.

        Dictionary<int, string> fruit = new Dictionary<int, string>();

  

        fruit.Add(1, "Kiwi");

        fruit.Add(2, "Pear");

        fruit.Add(3, "Mango");

        fruit.Add(4, "Blueberry");

        fruit.Add(5, "Apricot");

        fruit.Add(6, "Banana");

        fruit.Add(7, "Peach");

        fruit.Add(8, "Plum");

  

        // Define the binding for the list controls.

        MyListBox.DataSource = fruit;

      
/*
MyListBox.DataTextField = "Value";
MyListBox.DataValueField = "Key";
*/

// Choose what you want to display in the list. MyListBox.DataTextField = "Value"; // Activate the binding. this.DataBind(); } }

html code:

<select name="MyListBox" id="MyListBox" >

    <option value="1">Kiwi</option>

    <option value="2">Pear</option>

    <option value="3">Mango</option>

    <option value="4">Blueberry</option>

    <option value="5">Apricot</option>

    <option value="6">Banana</option>

    <option value="7">Peach</option>

    <option value="8">Plum</option>

</select>

 

你可能感兴趣的:(asp.net)