Domanda

I thought this would be easy and straightforward, but I seem to be having an issue with it.

Basically, I have this in a formview:

 <asp:TextBox ID="StatusTextBox" runat="server" Text='<%# Bind("Status") %>' /> 

And I want to replace it with this:

 <asp:DropDownList ID="StatusDropdown" runat="server">
       <asp:ListItem Selected="True" Value="A">Active</asp:ListItem>
       <asp:ListItem Value="I">Inactive</asp:ListItem>
  </asp:DropDownList>

I'm not exactly sure how to bind this like the Textbox is bound.

Is there a straightforward answer?

È stato utile?

Soluzione

Codebehind is not a hack, actually it's best practise since you have full control and compiler support (shows errors at compile time and avoids careless mistakes)

For example (assuming that the DropDownList is in the EditItemTemplate):

private void FormView1_DataBound(object sender, System.EventArgs e)
{
    switch (FormView1.CurrentMode)
    {
        case FormViewMode.ReadOnly:
            break;
        case FormViewMode.Edit:
            // note that the DataSource might be a different type
            DataRowView drv = (DataRowView)FormView1.DataSource;
            DropDownList StatusDropdown = (DropDownList)FormView1.FindControl("StatusDropdown");
            // you can also add the ListItems programmatcially via Items.Add
            StatusDropdown.DataSource = getAllStatus(); // a sample method that returns the datasource
            StatusDropdown.DataTextField = "Status";
            StatusDropdown.DataValueField = "StatusID";
            StatusDropdown.DataBind();
            StatusDropdown.SelectedValue = drv["StatusID"].ToString();
            break;
        case FormViewMode.Insert:
            break;
    }
}

Altri suggerimenti

Bind it to the SelectedValue property as so:

 <asp:DropDownList ID="StatusDropdown" runat="server" SelectedValue='<%# Bind("Status") %>'>

The value in status has to match the value of a drop down list item.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top