2

I am getting this error:

Cannot convert type 'string' to 'float'

on following lines of code:

float x=(float )(TextBox_item_price.Text);

How can I solve this?

4
  • 9
    Error message isn't clear? What is the value of TextBox_item_price.Text exactly? Commented Mar 27, 2014 at 9:05
  • 2
    Wow.. I just saw 8 answer (1 is deleted) and no one even care what is the value of TextBox_item_price.Text exactly and which Culture OP's using.. Commented Mar 27, 2014 at 9:21
  • @SonerGönül Well, we can guess that author uses locale on his PC he is aware of and types number into the textbox in that format. Commented Mar 27, 2014 at 9:26
  • Why are you needing to use a float? Surely a double would be better? Commented Apr 28, 2014 at 12:38

10 Answers 10

6

You need to do

float x = float.Parse(TextBox_item_price.Text);
Sign up to request clarification or add additional context in comments.

Comments

1

try this:

float f; 
float.TryParse(TextBox_item_price.Text, out f);

Comments

0

use this:

float x = float.Parse(TextBox_item_price.Text);

Comments

0

use Float.TryParse. This will return true if parsing is successful. Else false will be returned. No exception is thrown.

Like this

float x;
if (float.TryParse(TextBox_item_price.Text, out x))
{
            //success
}

Comments

0

it wil work fine

float x=float.Parse(TextBox_item_price.Text);

Comments

0

You can not use type casting between incompatible types, use Single.TryParse or Convert.ToSingle

To convert between non-compatible types, such as integers and System.DateTime objects, or hexadecimal strings and byte arrays, you can use the System.BitConverter class, the System.Convert class, and the Parse methods of the built-in numeric types, such as Int32.Parse.

Comments

0

try this:

var a = string.Empty;
var b = float.Parse(a);

Comments

0

Try This:

(float)System.Convert.ToSingle(TextBox1.Text);

or this:

float.Parse(TextBox1.Text);

Comments

0

try this:

You can use float.Parse() instead of using float x=(float)(); it will works fine

Comments

-1

try this;

Convert.ToDouble(TextBox_item_price.Text)

instead of;

(float)(TextBox_item_price.Text);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.