Not possible to load DropDownList on FormView from code behind?

前端 未结 3 1368
旧巷少年郎
旧巷少年郎 2021-01-13 10:19

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

Like so:



        
3条回答
  •  耶瑟儿~
    2021-01-13 10:37

    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:

    
    

    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:

    
        
            
        
    
    

    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 lst = new List();
        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").

提交回复
热议问题