Reputation: 46
I am creating a form to upload images. I have a dropdownlist fed by a SQL database, which contains the name and Id of previously created albums that the user may upload images into. If I select the second or lower option in the dropdownlist it always returns the correct Id, but if I leave the default option selected it always returns 0.
I feel like I'm missing something obvious here!
On page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["userId"] == null)
{
Response.Redirect("login.aspx");
}
else
{
BindDropDownList();
}
}
BindDropDownList method:
string qry2 = "SELECT Id, albumName FROM albums WHERE albumOwnerId=@albOwnId";
SqlCommand cmd2 = new SqlCommand(qry2, conn);
cmd2.Parameters.AddWithValue("@albOwnId", Session["userId"]);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
album.DataValueField = "Id";
album.DataTextField = "albumName";
album.DataSource = dt2;
album.DataBind();
album.SelectedItem.Value = dt2.Rows[0]["Id"].ToString();
albumData = Int32.Parse(album.SelectedItem.Value);
conn.Close();
}
Selected Index Changed Method:
protected void album_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList album = Page.FindControl("album") as DropDownList;
albumData = Int32.Parse(album.SelectedItem.Value);
}
ASP.net:
<asp:DropDownList ID="album" runat="server" OnSelectedIndexChanged="album_SelectedIndexChanged">
</asp:DropDownList><br />
Upvotes: 1
Views: 88
Reputation: 1989
After the discussion, I think the problem is that you handle the OnSelectedIndexChanged event and not the OnClick event of the button.
If you don't change the value of the dropdownlist the OnSelectedIndexChanged will not be raised.
You should handle the button OnClick event:
<asp:Button ID="btn" runat="server" Text="Go" OnClick="btn_Click" />
protected void btn_Click(object sender, EventArgs e)
{
DropDownList album = Page.FindControl("album") as DropDownList;
albumData = Int32.Parse(album.SelectedItem.Value);
}
Upvotes: 1