ASP.NET simple custom control with two way binding

偶尔善良 提交于 2019-12-12 18:11:56

问题


I have custom control with two textboxes and one drop down list. I want to make it two-way data bound, so when I put it into ie. Details View control like this:

    <asp:MyCustomControl ID="MyId" runat="server" Value1='<%# Bind("val1") %>'>
    </asp:MyCustomControl>

then it should work like regular TextBox..

In my control I have Value1 defined:

    [
    Bindable(true, BindingDirection.TwoWay),
    Browsable(true),
    DefaultValue(0),
    PersistenceMode(PersistenceMode.Attribute)
    ]
    public  double Value1
    {
        get
        {
            if(ViewState["Value1"]==null)
                return 0;
            return (double)ViewState["Value1"];                
        }
        set
        {
            ViewState["Value1"] = value;
        }
    } 

I want this control to keep simple.

What am I missing?


回答1:


I've found some kind of workaround. The property in control (ascx.cs) now looks like this:

    private double _value = 0;
    [
    Bindable(true, BindingDirection.TwoWay),
    Browsable(true),
    DefaultValue(0),
    PersistenceMode(PersistenceMode.Attribute)
    ]
    public double Value
    {
        get
        {
            double d = 0;
            Double.TryParse(ValueControlTextBox.Text,out d);
            return d;
        }
        set
        {   
            ValueControlTextBox.Text = String.Format("{0:0.00}", value);
            _value = value;
        }
    }

And that works as I need.



来源:https://stackoverflow.com/questions/7194364/asp-net-simple-custom-control-with-two-way-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!