Antonio Mailtraq
Antonio Mailtraq

Reputation: 1407

Selected value from database in DropDownList (not GridView)

I work in ASP NET 4.0 and C-sharp.

I have one form page .aspx with this DropDownList (Inside is the ID) and save the value S or N in the matching field in database :

<asp:DropDownList ID="Inside" runat="server" Width="100" CssClass="ddl_Class">
  <asp:ListItem Text="-------" Value=""></asp:ListItem>
  <asp:ListItem Text="S" Value="S"></asp:ListItem>
  <asp:ListItem Text="N" Value="N"></asp:ListItem>
</asp:DropDownList>

I need that when the value of field Inside in database is valid and is not null, in the DropDownList it's selected the value set in the database and disable the DropDownList.

I have tried this code in .cs page without success.

Anybody know how can I do that?

code-behind

InsideDB = dr["Inside"].ToString();
if (!string.IsNullOrEmpty(InsideDB.ToString()))
{
  Inside.Text = InsideDB.ToString();
  Inside.Enabled = false;
}
else
{
  Inside.Enabled = true;
}

Upvotes: 1

Views: 1110

Answers (3)

Manusha
Manusha

Reputation: 355

I know this is old post. But this may help others.

Inside.Items.FindByText(InsideDB.ToString()).Selected=true;
Inside.Enabled = false;

Upvotes: 0

Jahangeer
Jahangeer

Reputation: 478

Try SelectedValue instead of Text property.

InsideDB = dr["Inside"].ToString();
Inside.Enabled = true;
if (!string.IsNullOrEmpty(InsideDB.ToString()))
{
  Inside.SelectedValue = InsideDB.ToString();
  Inside.Enabled = false;
}

Upvotes: 2

Adrian Buzea
Adrian Buzea

Reputation: 836

Try something like

Inside.SelectedIndex = Inside.Items.IndexOf(Inside.Items.FindByText(InsideDB.ToString()));

instead of Inside.Text = InsideDB.ToString();

This assumes that you have an item with that text in the dropdownlist already.

Upvotes: 0

Related Questions