Link to home
Create AccountLog in
Avatar of SweatCoder
SweatCoderFlag for United States of America

asked on

can't get asp.net ListBox SelectedValue

No matter what I try, I can't get the SelectedValue from my listbox on postback. I have triple-checked and even verified by stepping through code that I'm not rebinding my listbox to the datasource on postback (button click).

listbox declaration:
<asp:ListBox ID="listAvailableAMCs" Rows="8" Width="300px" DataValueField="ID" DataTextField="Company" runat="server"></asp:ListBox>

Listbox data population works fine.

A button click calls this:

protected void LinkAMC(object sender, EventArgs e)
    {
        if(listAvailableAMCs.SelectedValue != string.Empty)
            Utilities.LinkAMC(int.Parse(listAvailableAMCs.SelectedValue));

        LoadGridData();
    }

SelectedValue is always blank. SelectedText is blank and SelectedIndex is -1.

A view source reveals this html:

<select size="8" name="ctl00$MasterMain$listAvailableAMCs" id="MasterMain_listAvailableAMCs" style="width:300px;">
      <option value="19">Como AMC</option>
      <option value="21">Sinatra AMC</option>
      <option value="20">Martin AMC</option>
</select>

Those option values and text values are exactly right.

What am I missing?
ASKER CERTIFIED SOLUTION
Avatar of Om Prakash
Om Prakash
Flag of India image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of SweatCoder

ASKER

1 is good, as mentioned in original post.
2 - viewstate is disabled for the whole site because I don't need. Maybe you've got a point here, but I use asp:DropDownList on other pages and it works fine with viewstate turned off. Why would ListBox be different from ddl in that respect?
3- Not sure exactly what you mean. If i'm not in a postback, that's when I bind the listbox.
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Else please post the complete Code behind Code so that I can help you out much better
I am only binding data source when not in a postback:

if (!IsPostBack)
        {
            listAvailableAMCs.DataSource = Utilities.GetLinkedAMCs(_LenderBrokerID);
            listAvailableAMCs.DataBind();
        }

I have noticed that everything works fine when I use a declarative data source in the aspx, but this becomes awkward. I'd rather get my data from a class library where I can do some logic checks, pass in variables, parameterize the query, etc.
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Had to use javascript, asp.net solution never worked. Awarding points just so I can close this.