how to bind a double property to text box in C#..

Dani AI

Generated

Thread mixes WebForms-style attribute advice and WinForms data-binding. ’s suggestion about adding attributes affects rendered HTML attributes (useful for presentation) but does not perform type conversion or two‑way data binding. ’s prompt about “double property” is important: a numeric property of type double (for example an Amount field) needs conversion to and from the TextBox’s string Text. The right approach depends on whether this is WinForms or ASP.NET Web Forms.

For WinForms, bind the TextBox Text to the double property with formatting enabled and handle conversion on Format/Parse (or use the Add overload that accepts a format string). Example using Binding with explicit handlers:

using System.Globalization;
using System.Windows.Forms;

var bind = new Binding("Text", myObject, "Amount");
bind.FormattingEnabled = true;
bind.Format += (s, e) =>
{
    if (e.Value is double d) e.Value = d.ToString("N2", CultureInfo.CurrentCulture);
};
bind.Parse += (s, e) =>
{
    double v;
    if (double.TryParse(Convert.ToString(e.Value), NumberStyles.Any, CultureInfo.CurrentCulture, out v))
        e.Value = v;
    else
        e.Value = 0.0;
};
textBox1.DataBindings.Add(bind);

See the Binding.Format and Binding.Parse docs for details: Binding.Format and Binding.Parse. The Control.DataBindings.Add overload that accepts a format string is also useful: [ControlBindingsCollection.Add overload](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.controlbindingscollection.add?view=windowsdesktop-7.0#system-windows-forms-controlbindingscollection-add(system-string-system-object-system-string-system-boolean-system-windows-forms-datasourceupdatemode-system-object-system-string).

For ASP.NET Web Forms, either use a data-binding expression inside a template (for two-way binding inside FormView/DetailsView) or assign/parse in code-behind:

double amount;
if (!double.TryParse(txtAmount.Text, NumberStyles.Any, CultureInfo.CurrentCulture, out amount))
    amount = 0.0;
businessObject.Amount = amount;

General pitfalls: missing INotifyPropertyChanged on the business object prevents UI updates (see INotifyPropertyChanged); mismatched culture/decimal separators will break parsing (use CultureInfo); formatting only applies when FormattingEnabled is true; ensure the bound DataSource instance and property name match. For Web Forms patterns and templates see .

Recommended Answers

All 3 Replies

If you want to set properies dynamically in c#, try this ,

TextBox_Id.Attribute.Add("Property Name","Propery Value");

Can add one or more properties like this..

Hi,

please define what do you call a double property.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.