Wrong value from DropDownList, SQL Server
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 cho开发者_StackOverflowose 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)
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
.
精彩评论