user2158735
user2158735

Reputation: 47

populate DropDownList with a list

I'm trying to populate a DropDownList with a List that a user makes. A user types a ball name and its weight and is then added on a list box. In the Default page I have:

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());
    }

and in my Ball Class:

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"
    }

How can I, in another class with a DropDownList, populate it with the Ball names from default class?

Upvotes: 0

Views: 90

Answers (1)

Luaan
Luaan

Reputation: 63732

The same way you do it with the ListBox - in fact, the two are almost identical in 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());
  }
}

Upvotes: 1

Related Questions