2013-11-26 113 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