2013-11-26 146 views
0

我正在嘗試使用List來填充DropDownList。用戶輸入球的名稱及其重量,然後添加到列表框中。在默認的網頁我有:使用列表填充DropDownList

List<Ball> myBall; 
protected void Page_Load(object sender, EventArgs e)   
{ 
    if (!Page.IsPostBack) 
     { 
      myBall = new List<Ball>(); 
      Session["listSession"] = myBall; 
     } 
} 

protected void Button1_Click(object sender, EventArgs e) 
{ 
    ListBox1.Items.Clear(); 
    Ball f = new Ball(TbxName.Text, int.Parse(TbxWeight.Text)); 
    myBall= (List<Ball>)Session["listSession"]; 
    myBall.Add(f); 
    foreach (var item in myBall) 
    { 
     ListBox1.Items.Add(item.getBallInfo()); 
    } 

,並在我的球類:

public Ball(string n, int w) 
{ 
    name = n; 
    weight = w; 
} 

public string getBallInfo() 
{ 
    string s; 
    if (weight > 5) 
    { 
     s = name + " is huge" 
    } 
    else 
    { 
    s = name + " is small" 
    } 

我如何,與DropDownList另一個類,從默認類球名稱來填充呢?

回答

1

就像你用ListBox做的那樣 - 事實上,兩者在HTML中幾乎相同。

protected void Page_Load(object sender, EventArgs e)   
{ 
    if (!Page.IsPostBack && Session["listSession"] != null) 
    { 
    var myBall = (List<Ball>)Session["listSession"]; 
    foreach (var ball in myBall) 
     DropDownList1.Items.Add(item.getBallInfo()); 
    } 
} 
+0

感謝您的時間和回答 – user2158735

+0

不客氣:) – Luaan