Reputation: 43
So i'm using dropdownlist control by assigning array of string to it. The coding for it i wrote in Page_Load function.
protected void Page_Load(object sender, EventArgs e)
{
string[] Gender = { "Male", "Female" };
DdlGender.DataSource = Gender;
DdlGender.DataBind();
string[] Update = { "Yes", "No" };
DdlUpdates.DataSource = Update;
DdlUpdates.DataBind();
}
and now i want to know how to display the selected string accurately in the dropdownlist after i pressed the button?
Also i'm using this coding to display, it would only display the first string when i selected the second string in the dropdownlist...
protected void BtnSubmit_Click(object sender, EventArgs e)
{
int i;
lblGender.Text = DdlGender.Text;
lblUpdates.Text = DdlUpdates.Text;
}
Upvotes: 0
Views: 134
Reputation: 35514
You have to wrap the databinding of the DropDownLists in a IsPostBack
check. Otherwise they will be recreated on PostBack and their selected value will be lost. That is why you always get the first string.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string[] Gender = { "Male", "Female" };
DdlGender.DataSource = Gender;
DdlGender.DataBind();
string[] Update = { "Yes", "No" };
DdlUpdates.DataSource = Update;
DdlUpdates.DataBind();
}
}
And you can get the values on the button click with SelectedValue
.
DdlUpdates.Text = DdlGender.SelectedValue;
DdlUpdates.Text = DdlUpdates.SelectedValue;
It can also be done like this: DdlGender.SelectedItem.Text
, but usually a DropDownList is a KeyValue pair where you use the value, not the text. Here an example.
<asp:DropDownList ID="DdlGender" runat="server">
<asp:ListItem Text="I'm a male" Value="M"></asp:ListItem>
<asp:ListItem Text="I'm a female" Value="F"></asp:ListItem>
</asp:DropDownList>
In this examplet he user gets a lot more Text
in the DropDownList, but we don't need that in the database, so we set the Values
to just M
and F
.
Upvotes: 1
Reputation: 1507
Try use SelectedItem
property instead:
protected void BtnSubmit_Click(object sender, EventArgs e)
{
lblGender.Text = DdlGender.SelectedItem.ToString();
lblUpdates.Text = DdlUpdates.SelectedItem.ToString();
}
Upvotes: 1