无法将“system.windows.forms.textbox”类型的对象强制转换为c#表单的“System.IConvertible”错误

时间:2017-09-26 23:22:54

标签: c# object casting

我在这里有这个代码,但我一直得到同样的错误。谁能告诉我我做错了什么?

private void button1_Click(object sender, EventArgs e)
{
    double gallonsToBuy;//for equation
    double WALL_LENGTH; //holds wall length
    double WALL_HEIGHT; //holds wall height
    int    NUM_DOORS;   //holds number of doors
    int    NUM_WINDOWS; //holds number of windows
    int    NUM_COATS;   //holds number of coats of paint
    const double GALLON_SF = 350; //one gallon covers 350 square feet

    //allows user to input their numbers
    WALL_LENGTH = Convert.ToDouble(textBox1);
    WALL_HEIGHT = Convert.ToDouble(textBox2);
    NUM_DOORS =   Convert.ToInt32(textBox3);
    NUM_WINDOWS = Convert.ToInt32(textBox4);
    NUM_COATS =   Convert.ToInt32(textBox5);

    //Equation
    gallonsToBuy = ((((WALL_LENGTH * WALL_HEIGHT) - (20 * NUM_DOORS) - (15 * NUM_WINDOWS)) * NUM_COATS) /350);

    label7.Text = "Gallons to buy =" +gallonsToBuy;
}

2 个答案:

答案 0 :(得分:2)

您的错误来自于尝试将TextBox转换为double

WALL_LENGTH = Convert.ToDouble(textBox1);

TextBox是.NET对象类型,您无法对double进行有意义的转换。您必须做的是将TextBox.Text属性的值转换为double

WALL_LENGTH = Convert.ToDouble(textBox1.Text);

但是如果用户输入的文字无法转换为double,那么仅此一项仍有问题且容易出错。

因此,您应该使用适当的转换方法,例如int.TryParse()double.TryParse()

例如,

double WALL_LENGTH;
double.TryParse(textBox1.Text, out WALL_LENGTH);

如果所有此类转换都成功,则继续进行计算。

答案 1 :(得分:1)

查看你的代码我相信textBox1,textBox1等是TextBox控件。您无法将控件类型转换为数据类型。您需要使用属性.text来访问控件中的值。

    WALL_LENGTH = Convert.ToDouble(textBox1.Text);
    WALL_HEIGHT = Convert.ToDouble(textBox2.Text);
    NUM_DOORS =   Convert.ToInt32(textBox3.Text);
    NUM_WINDOWS = Convert.ToInt32(textBox4.Text);
    NUM_COATS =   Convert.ToInt32(textBox5.Text);

确保你有一个输入字段的值,否则它会通过强制转换错误尝试从string.empty转换它。