I have a text box designTB and a double variable totaldsgn.
I cannot create the following equation because the designTB is a string and totaldsgn is a double

designTB.Text = totaldsgn

I have tried this and it still does not work

designTB.Text = totaldsgn.tostring

Any suggestions? Is there a way to make a text box a double instead of a string?

Dani AI

Generated

— the TextBox holds text, so you must convert between string and numeric types. is right to stress validation; below are a couple of practical alternatives depending on whether you only need to display a value or accept edited numeric input.

If the user should pick or edit a number, use a NumericUpDown control instead of a plain TextBox. It uses a numeric type (decimal) internally and avoids parsing headaches:

numericUpDown1.DecimalPlaces = 2;
numericUpDown1.Minimum = -1000000;
numericUpDown1.Maximum = 1000000;
numericUpDown1.Value = (decimal)totaldsgn;   // set display

// read back
totaldsgn = (double)numericUpDown1.Value;

For data-driven UIs where you bind a double property to a TextBox, attach Format and Parse handlers to the Binding so the UI shows a formatted string and the model receives a parsed double (handle parse errors in the Parse handler):

using System.Globalization;

var binding = new Binding("Text", model, "TotalDesign", true, DataSourceUpdateMode.OnPropertyChanged);

binding.Format += (s,e) => {
  if (e.Value is double d) e.Value = d.ToString("F2", CultureInfo.CurrentCulture);
};

binding.Parse += (s,e) => {
  try { e.Value = double.Parse((string)e.Value, CultureInfo.CurrentCulture); }
  catch { e.Value = 0.0; } // handle invalid input as you prefer
};

textBox1.DataBindings.Add(binding);

Troubleshooting notes: C# is case-sensitive — call ToString() (capital T and parentheses). Consider decimal instead of double for money to avoid precision issues. Use culture-aware parsing/formatting so decimal separators match the user locale. For interactive validation keep focus with the Validating event and an ErrorProvider so users correct bad input before continuing.

See the NumericUpDown docs for details: NumericUpDown documentation.

Recommended Answers

All 2 Replies

Without databinding you need to validate the input yourself:

private void button1_Click(object sender, EventArgs e)
    {
      //Set the value
      double d1 = 5.0;
      textBox1.Text = Convert.ToString(d1);
    }

    private void button2_Click(object sender, EventArgs e)
    {
      //read the value
      double d1;
      if (!double.TryParse(textBox1.Text, out d1))
      {
        textBox1.Focus();
        textBox1.SelectAll();
        MessageBox.Show("Invalid value");
        return;
      }
      //Continue with code...
    }

Thanks sknake

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.