ListBox.SelectedItem.Value Does Not Work

Results 1 to 2 of 2

Thread: ListBox.SelectedItem.Value Does Not Work

  1. #1
    Join Date
    Dec 1969

    Default ListBox.SelectedItem.Value Does Not Work

    The ListBox.SelectedItem.Value property does not return a correct value when bound to a data source. For example:<BR><BR>void Page_Load(object sender, EventArgs e) {<BR> ListBox1.DataSource = ds;<BR> ListBox1.DataValueField = "ItemID"<BR> ListBox1.DataTextField = "ItemName";<BR> ListBox1.DataBind();<BR>}<BR><BR>void Button1_Click(object sender, EventArgs e) {<BR> if (ListBox1.SelectedIndex != -1) {<BR> // *** This throws an exception ***<BR> Label1.Text = "Selected Item Value: "<BR> + ListBox1.SelectedItem.Value;<BR> }<BR>}<BR><BR>However, if I use the following, I can get the value:<BR><BR>void Button1_Click(object sender, EventArgs e) {<BR> if (ListBox1.SelectedIndex != -1) {<BR> Label1.Text = "Selected Item Value: "<BR> + ListBox1.Items[<BR> ListBox1.SelectedIndex].Value;<BR> }<BR>}<BR><BR><BR>May I know if I did something wrong to use the first <BR>approach?<BR><BR>[ Note that the 1st method does not work when the list box is data bound. If the items are created using the Add method, the 1st method will work perfectly. ]<BR><BR><BR>Thanks.<BR>

  2. #2
    Join Date
    Dec 1969

    Default RE: ListBox.SelectedItem.Value Does Not Work

    cuz you are binding on every page load. Try binding only if !IsPostBack

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts