views:

82

answers:

2

The following code is for winforms:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            listBox1.DataSource = Fruit.Get();
            listBox1.DisplayMember = "Name";
            listBox1.ValueMember = "ID";
        }

        private void listBox1_Click(object sender, EventArgs e)
        {
            object li = listBox1.SelectedItem;

            Fruit fr = (Fruit) li;

            label1.Text = fr.Name;
        }
    }

Is it possible to use the same technique in asp.net?

If no, then what is the alternative?

+2  A: 

No, it's not possible in ASP.NET.

As an alternative, you can store your fruit items in Dictionary<string, Fruit> collection and you can get your selected Fruit like that :

// Assume that your datasource is Dictionary<string, Fruit> myFruits
Fruit fr = myFruits[listBox1.SelectedValue];
Canavar
A: 

I don't think you can do it exactly like that, as I'm quite rusty in winforms, but here's how i'd try it in asp.net

1.) Bind your listbox in Page_PreRender()

listBox1.DataSource = Fruit.Get();
listBox1.DataTextField = "Name";
listBox1.DataValueField = "ID";
listBox1.DataBind();

2.) I'm not sure what the equivalent "OnClick" event would be, but you could hook into the SelectedIndexChanged event like so (triggered by another button):

var li = listBox1.SelectedItem;
label1.Text = li.Text;

Jim B
Well, I did this already. I was just searching for a better technique. I.e. to work with objects.
JMSA
Meanwhile, Canavar's technique is very good. It solves a lot of problems.
JMSA