开发者

Binding a DropDownList inside a DetailsView

I'm having problems trying to populate a dropdownlist from the database. When I'm trying to set the datasource I can't find the dropdown control, it's in a DetailsView so I think it might have something to do with it only being created when it's in edit mode. It still says it's in current mode when I'm editing though, so not sure what's going on there.

Here's the code from the aspx file:

<asp:DetailsView id="开发者_JS百科DetailsView1" runat="server" AutoGenerateRows="false" DataSourceID="myMySqlDataSrc"  DataKeyNames="id" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" AutoGenerateInsertButton="False" >
     <Fields>
        <asp:TemplateField HeaderText="Region">
            <ItemTemplate><%# Eval("region_name") %></ItemTemplate>
            <EditItemTemplate>
                <asp:DropDownList ID="RegionDropdownList" runat="server" SelectedValue='<%# Bind("region_id")%>' />
            </EditItemTemplate>
        </asp:TemplateField>        
     </Fields>
</asp:DetailsView>

And this is from the code behind:

ArrayList regionsList = BPBusiness.getRegions();
if (DetailsView1.CurrentMode == DetailsViewMode.Edit)
{
    DropDownList ddlRegions = (DropDownList)DetailsView1.FindControl("RegionDropdownList");
    if (ddlRegions != null)
    {
        ddlRegions.DataSource = regionsList;
        ddlRegions.DataBind();
    }
}


If it isn't already, place the sample from your code behind inside the DetailsView1_ModeChanged or DetailsView1_DataBound method. If it is in the DetailsView1_ModeChanging method, the mode has not actually changed yet.

EDIT: Also, make sure you set up the DataTextField and DataValueField like so:

DropDownList1.DataTextField = "TextFieldName";
DropDownList1.DataValueField = "ValueFieldName";

Also remove the SelectedValue bind; it does nothing except throw errors.

EDIT 2: If you really need to select a particular value of the dropdownlist when it first is databind, you could do something like this:

if(DropDownList1.Items.Contains(DropDownList1.Items.FindByValue("Value")))
{
    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue("Value));
}


try doing it in the itemcreated method

protected void DetailsView1_ItemCreated(object sender, EventArgs e)
{
    ArrayList regionsList = BPBusiness.getRegions();
    if (DetailsView1.CurrentMode == DetailsViewMode.Edit)
    {
        DropDownList ddlRegions = (DropDownList)DetailsView1.FindControl("RegionDropdownList");
        if (ddlRegions != null)
        {
            ddlRegions.DataSource = regionsList;
            ddlRegions.DataBind();
        }
    }
}

remember to set OnItemCreated="DetailsView1_ItemCreated"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜