1

I get the wrong value from my Dropdownlist (ddlCity). I always get the "default" value, the value the list has when the page load. What am I doing wrong?

<asp:DropDownList ID="ddlCountry" runat="server"AutoPostBack="true"></asp:DropDownList>

<asp:DropDownList ID="ddlCity" runat="server"></asp:DropDownList>

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataTable CountryTable = CategoryAccess.GetCountry();
        ddlCountry.DataSource = CountryTable;
        ddlCountry.DataTextField = "CountryName";
        ddlCountry.DataValueField = "CountryID";
        ddlCountry.DataBind();
    }
    else
    {
        String CountryID = ddlCountry.SelectedValue;

        DataTable CityTable = CategoryAccess.GetCitysInCountry(CountryID);
        ddlCity.DataSource = CityTable;
        ddlCity.DataTextField = "City";
        ddlCity.DataValueField = "CityID";
        ddlCity.DataBind();
    }
}

protected void btnUpdate_Click(object sender, EventArgs e)
{
    string id = (ddlCity.SelectedItem.Value);
    //This is where id is wrong, unless I choose the first city in the list.
}

Database code:

ALTER PROCEDURE GetCountry
AS          
SELECT        CountryID, CountryName
FROM          tblCountry  



ALTER PROCEDURE GetCitysInCountry
@CountryID INT
AS          
SELECT        tblCitysInCountry.CityID, tblCitysInCountry.CountryID, tblCity.City, tblCountry.CountryName
FROM          tblCitysInCountry LEFT JOIN
                         tblCity ON tblCitysInCountry.CityID = tblCity.CityID LEFT JOIN
                         tblCountry ON tblCitysInCountry.CountryID = tblCountry.CountryID
WHERE         (tblCitysInCountry.CountryID = @CountryID)
1
  • From your code comment it looks like your problem is CityID. Is this the case? Or is it CountryID? Commented Sep 19, 2011 at 13:18

1 Answer 1

1

Page_Load occurs before the selected index is set during postback. Try moving your second set of databinding code to a more appropriate place - maybe in the event handler that ddlCountry will be invoking (SelectedIndexChanged?)


There certainly seem to be a lot of hits on Google for "page_load SelectedValue", which all tend to indicate the value cannot be accessed during Page_Load.

Sign up to request clarification or add additional context in comments.

1 Comment

Understanding the page lifecycle will make you a MUCH happier (and more effective) asp.net programmer. :) msdn.microsoft.com/en-us/library/ms178472.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.