Reputation: 16968
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?
Upvotes: 0
Views: 248
Reputation: 8584
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;
Upvotes: 0
Reputation: 48088
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];
Upvotes: 2