views:

830

answers:

3

I have a UserControl, containing a FormView, containing a DropDownList. The FormView is bound to a data control.

Like so:

    <asp:FormView ID="frmEdit" DataKeyNames="MetricCode" runat="server" 
    DefaultMode="Edit" DataSourceID="llbDataSource" Cellpadding="0" >
    <EditItemTemplate>
    <asp:DropDownList ID="ParentMetricCode"  runat="server" SelectedValue='<%# Bind("ParentMetricCode") %>' /> 

etc, etc

I am trying to populate the DropDownList from the codebehind. If this was not contained in a FormView, I would normally just do it in the Page_Load event. However, that does not work within a FormView, as as soon as I try to do it, accessing the dropdownlist in code, ie:

theListcontrol = CType(formView.FindControl(listControlName), System.Web.UI.WebControls.ListControl)  

...the data binding mechansim of the FormView is invoked, which, of course, tries to bind the DropDownList to the underlying datasource, causing a *'ParentMetricCode' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value * error, since the DropDownList has not yet been populated.

I tried performing the load in the DataBinding() event of the FormView, but then:

theListcontrol = CType(formView.FindControl(listControlName), System.Web.UI.WebControls.ListControl)

...fails, as the FormView.Controls.Count = 0 at that point.

Is this impossible? (I do not want to have to use a secondary ObjectDataSource to bind the dropdownlist to)

A: 

Implement the OnDataBinding directly on your DropDownList.

When you bind your formview to some data the OnDataBinding for the DropDownList will fire. At this point you can then load the the values you want into the list and bind the selected value to the loaded list as well.

Here is an example:

<asp:DropDownList ID="ParentMetricCode"  runat="server" OnDataBinding="ParentMetricCode_DataBinding" />

Then implement the OnDataBinding:

protected void ParentMetricCode_DataBinding(object sender, System.EventArgs e)
{            
    DropDownList ddl = (DropDownList)(sender);

    // Fill the list items however you want
    ddl.Items.Add(new ListItem("1", "1"));
    ddl.Items.Add(new ListItem("2", "2"));
    // etc...

    // Set the selected value
    ddl.SelectedValue = Eval("ParentMetricCode").ToString();
}

When DataBind your FormView, everything will start to do its magic :)

Also if you loading the list data for your DropDownList from a DB or something you might want to cache it since each 'row' of data will cause the loading of the list data.

EDIT: Since you think it's not possible I wrote a quick demo app to prove how it works:

In your aspx file include this:

<asp:FormView ID="fvTest" runat="server">
    <ItemTemplate>
        <asp:DropDownList ID="ddlTest" runat="server" OnDataBinding="ddlTest_DataBinding"></asp:DropDownList>
    </ItemTemplate>
</asp:FormView>

Then in your .cs file:

public class MockData
{
    public string ID { get; set; }
    public string Text { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    List<MockData> lst = new List<MockData>();
    lst.Add(new MockData() { ID = "3", Text = "Test3" });
    fvTest.DataSource = lst;
    fvTest.DataBind();
}

protected void ddlTest_DataBinding(object sender, System.EventArgs e)
{
    DropDownList ddl = (DropDownList)(sender);
    ddl.Items.Add("1");
    ddl.Items.Add("2");
    ddl.Items.Add("3");
    ddl.Items.Add("4");
    ddl.Items.Add("5");

    ddl.SelectedValue = Eval("ID").ToString();
 }

Run the code... the DropDownList will be loaded with all the values and be set to the correct selected value that was set in the mocked object.

Not sure what else I can do to prove it any better... I think your missing how DataBinding actually works. If you try to do it at the FormView level, the controls don't get made until the FormView is actually bound. When the binding happens, you can trigger each control within the template to do something by implementing it's OnDataBinding event. At that point the current iteration of bound object and it's values are available and that is where you see my code do an Eval("ID").

Kelsey
Unfortunately, cannot do that....controls on a FormView are not visible from the code behind....thats why one must do: theListcontrol = CType(formView.FindControl(listControlName), System.Web.UI.WebControls.ListControl)....which then gets me back into the mess of, when can I get access to this control (ie: it HAS been created), but BEFORE the actual FormView databind happens. If the FormView was not involved here, your example would work....but then, I wouldn't be having this problem! :)
tbone
It should work just like a gridview. You don't have access directly but through the onDataBinding method you do. Try it, it works. This is how all bindable template controls work.
Kelsey
This is where you fall down though: ddl.SelectedValue = Eval("ID").ToString();You've lost two way databindingI think, right? Otherwise, why would you do that?And in your example code, you are using DropDownList.Add(ListItem) syntax...which, in the example I gave is what I did also, because it seems what the problems is is you can't mix your "DataBind" types. I may have been able to do mine in a different event, but its academic at this point, I just wanna get this working.But your line of code: ddl.SelectedValue = Eval("ID").ToString(); to me fails.
tbone
How does `ddl.SelectedValue = Eval("ID").ToString();` fail??? This is how you pull out the bound data form the current item by name without using the auto assignment which is really just doing it in the background. I don't see how doing `Bind("ParentMetricCode")` is any better... that is more of a fail to me.
Kelsey
What I meant was, you lose two way databinding in your implementation. Correct?
tbone
A: 

Ok, found "a" solution:

  1. Call the DDL populate function from the FormView_ItemCreated event.

  2. Modify the code to populate the DDL like so:

    Public Overloads Shared Sub BindListControl(Of theLLBLgenEntityType As EntityBase) _ (ByVal formView As FormView, _ ByVal listControlName As String, _ ByVal theCollection As CollectionCore(Of theLLBLgenEntityType), _ ByVal DataValueField As EntityField, _ ByVal DataTextField As EntityField, _ ByVal IncludeEmptyItem As Boolean)

    If formView.CurrentMode = FormViewMode.Edit Then
        Dim theListcontrol As System.Web.UI.WebControls.ListControl
        theListcontrol = CType(formView.FindControl(listControlName), System.Web.UI.WebControls.ListControl)
    
    
    
    For Each entity As theLLBLgenEntityType In theCollection
        theListcontrol.Items.Add(New ListItem(entity.Fields(DataTextField.Name).CurrentValue.ToString, entity.Fields(DataValueField.Name).CurrentValue.ToString))
    Next
     If IncludeEmptyItem Then theListcontrol.Items.Insert(0, New ListItem("", ""))
    
    End If

    End Sub

It kinda seems to basically boil down to, you cannot do additional "Databinding", programatically at runtime, within a FormView.

(Anyone know why the formatting of my code is all screwed up in this post??)

Update

This solution raises yet another batch of issues, related to inserting new items. After a lot of screwing around I eventually found a way around that. At this point, I am basically at the point where I would recommend either avoiding the FormView control entirely, or definitely avoid programatically altering bound controls. Hopefully, perhaps using seperate data controls for each DropDownList might work better, but this might be wishful thinking as well.

tbone
A: 

Thanks, that worked!

MAbraham1