Link to home
Start Free TrialLog in
Avatar of jumprooster
jumprooster

asked on

I need to set the value of DropDownList.SelectedIndex and I get either error read only or nothing changes.

I'm programming in ASP.net and C#.

I have the DropDownList on a WebForm.
There are 2 DropDownLists and TextBoxes on this WebForm.

The user clicks on Edit and the WebForm with the DropDownList loads.
The textboxes get filled with the data for the record the user selected on the the previous page.
The two DropDownLists get populated on the Page_Load with multiple values from the database.

The first item in this list says -Select- and the others below it say -Nissan-, -Ford- and -BMW-.
So I think the -Select- has the index of 0 Nissan 1 Ford 2 BMW 3.

What should happen is that when the page loads, one of the texts like Nissan Ford or BMW should be selected in the list instead of -Select-, according to the record selected from the previous page

The furthest I have gotten is with this code, which is within a function, which is called on the Page_Load event:

Models oCatalog = new Model();
SqlDataReader dr = oCatalog.GetCatalog(idCompany);                   
while(dr.Read())
{      

ddlIDCompany.SelectedIndex=ddlIDCompany.Items.IndexOf(ddlIDCompany.Items.FindByText(dr["ModelName"].ToString()));
}
which does nothing

however when I place ddlIDCompany.Items.IndexOf(ddlIDCompany.Items.FindByText(dr["ModelName"].ToString()));

in a Response.Write() it returns 1,2 or 3 depending on the record the user had selected on the previous page

This one´s a doozy for me.
Avatar of jaynus
jaynus

Is this being executed on a postback or every load, and before or render?
Avatar of jumprooster

ASKER

It's being executed in the initial Page_Load like this:

private void Page_Load(object sender, System.EventArgs e)
{
            
 if(!Page.IsPostBack)
ExecuteAction();

}

public void ExecuteAction()
{
ChrgFormModel();
}

public void ChrgFormModel()
{
Models oCatalog = new Model();
SqlDataReader dr = oCatalog.GetCatalog(idCompany);                
while(dr.Read())
{    

ddlIDCompany.SelectedIndex=ddlIDCompany.Items.IndexOf(ddlIDCompany.Items.FindByText(dr["ModelName"].ToString()));
}


}
ASKER CERTIFIED SOLUTION
Avatar of dungla
dungla
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yep, you can use teh ListItem class to insert items into a dropdownlist programatically including the selected item.

:)