System windows forms textbox ошибка

  • Remove From My Forums
  • Question

  • I use Microsoft Visual Basic 2008, and I had an error:

    Error 1 Value of type ‘System.Windows.Forms.TextBox’ can not be converted to ‘String’.

    how can I solve it? Please help me

Answers

  • Hi if you are trying to set a string variable to the a TextBox use the TextBox.Text property instead.

    Dim str as String
    str = Textbox1.Text;

    • Proposed as answer by

      Saturday, May 23, 2015 4:40 PM

    • Marked as answer by
      Youjun Tang
      Tuesday, June 2, 2015 9:37 AM

  • I use Microsoft Visual Basic 2008, and I had an error:

    Error 1 Value of type ‘System.Windows.Forms.TextBox’ can not be converted to ‘String’.

    how can I solve it? Please help me

    System.Windows.Forms.TextBox is a TextBox, not a string. You probably want the Text property of the TextBox (the string that the user entered). For example.

    Label1.Text = "The user typed " & TextBox1.Text

    • Proposed as answer by
      Magnus (MM8)MVP
      Saturday, May 23, 2015 12:39 PM
    • Marked as answer by
      Youjun Tang
      Tuesday, June 2, 2015 9:37 AM

Trying to make a money counter on C# and getting an error with an integer called costofcredit, i have declared this as an int I then have a button which i click and it will add 1p on and within this button i have the code of
costofcredit = Convert.ToInt32(textCPC);
and this is where i get the message below is my whole code

if (textCPC.Text != "0") 
            {
                onepence = onepence + 1
                label1p.Text = onepence.ToString(); 
                totalpence = totalpence + 1; 
                textTPV.Text = totalpence.ToString(); 
                totalpounds = totalpence / 100; 
                textTPVal.Text = totalpounds.ToString("n2"); 
                costofcredit = Convert.ToInt32(textCPC); 
                amountofcredits = Convert.ToInt32(totalpence) / costofcredit; 
                textAPC.Text = amountofcredits.ToString(); 
            else 
            {
                MessageBox.Show("Please enter the cost per credit!"); 
            }

Hans Passant's user avatar

Hans Passant

918k145 gold badges1681 silver badges2525 bronze badges

asked Jul 5, 2018 at 18:41

dave's user avatar

3

Because textCPC TextBox class did’t implementSystem.IConvertible interface.

When you use Convert.ToInt32 the object need to implement System.IConvertible

Convert.ToInt32(textCPC.Text); 

instead of

Convert.ToInt32(textCPC);

answered Jul 5, 2018 at 18:43

D-Shih's user avatar

D-ShihD-Shih

44.6k6 gold badges29 silver badges50 bronze badges

6

As I already said in the comments, you need to convert the .Text property of textCPC like so Convert.ToInt32(textCPC.Text) which if the Value of textbox textCPC is an integer value will work, seeing how you aren’t using a try catch for exception handling you may want to use System.Int32.TryParse in case the user enters something non-integer:

//Declare an out parameter of type int
int outIntCheck = 0;

//Check to see if you can successfully parse an integer value
if(System.Int32.TryParse(textCPC.Text, out outIntCheck)
   costofcredit = outIntCheck;
else
   //Show incorrect integer format error 

answered Jul 5, 2018 at 18:49

Ryan Wilson's user avatar

Ryan WilsonRyan Wilson

10.2k2 gold badges20 silver badges40 bronze badges

5

You are trying to convert the textCPC itself (which is a TextBox control) to an integer value while you should convert it’s value by using textCPC.Text. So just change

Convert.ToInt32(textCPC); 

To

Convert.ToInt32(textCPC.Text); 

Try to use [Int32.TryParse]1 so that when you input incorrect data it won’t through an exception. Or just use it inside a try/catch statement.

answered Jul 5, 2018 at 18:47

Peter Tovar's user avatar

1

You are using textCPC which I believe is a TextBox. You need value of the TextBox so should use textCPC.Text.

Milo's user avatar

Milo

3,3459 gold badges29 silver badges44 bronze badges

answered Jul 5, 2018 at 18:45

Kedar Rudre's user avatar

1

private void saveButton_Click(object sender, EventArgs e)

{

        TaskEmployee taskEmployee = new TaskEmployee();
        TaskEmployeeBLL taskEmployeeBLL = new TaskEmployeeBLL();
        Task1 task1 = new Task1();

        int employeeid = Convert.ToInt32(employeeNameShowComboBox.SelectedValue);

        bool save = false;

        foreach (ListViewItem itemRow in taskShowListView.Items)
        {

            if (itemRow.Selected == true)
            {
                int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);
                string taskDate = itemRow.SubItems[1].ToString();
                string taskDescription = itemRow.SubItems[2].ToString();

                task1.TaskID = taskId;
                task1.TaskDate = taskDate;
                task1.TaskDescription = taskDescription;

                taskEmployee.EmployeeId = employeeid;
                save = taskEmployeeBLL.TaskEmployeeSaveShow(taskEmployee, task1);

            }

        }


        if (save)
        {
            MessageBox.Show("save success");

        }
        else
        {
            MessageBox.Show("Don't save");
            return;
        }



    }

Theo's user avatar

Theo

57.2k8 gold badges24 silver badges41 bronze badges

answered Nov 18, 2019 at 12:43

TaTa's user avatar

TaTaTaTa

111 silver badge4 bronze badges

1

Your error comes from trying to convert a TextBox to a double.

WALL_LENGTH = Convert.ToDouble(textBox1);

TextBox is a .NET object type, and you cannot do a meaningful conversion to a double. What you must do is convert the value of TextBox.Text property to a double.

WALL_LENGTH = Convert.ToDouble(textBox1.Text);

But this alone would still be problematic and error prone, if the user enters text that cannot be converted to a double.

So you should, in addition, use proper methods for conversion such as int.TryParse() and double.TryParse().

For instance,

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

If all such conversions succeed, then proceed with the calculation.

Для того, чтобы разобраться, где возникает ошибка в этом коде:

shoeseTableAdapter.Insert(
    idshoes, 
    textBox_madein.Text, 
    textBox_material.Text, 
    textBox_size.Text, 
    Convert.ToInt32(textBox_quantity.Text),
    sex, 
    Convert.ToByte(s2[0]), 
    Convert.ToInt32(textBox_price.Text), 
    textBox_model.Text);

Я бы предложил сделать следующее: вынести передаваемые параметы, которые вы конвертируете при передаче, в отдельные переменные, чтобы удостовериться, что там все работает хорошо. Но и это еще не все, удостоверьтесь, что вы передаете правильные типы данных в метод.

var quantity = Convert.ToInt32(textBox_quantity.Text);
var sTwo = Convert.ToByte(s2[0]); // предполагаемое место ошибки
var price = Convert.ToInt32(textBox_price.Text);

// если до метода ваш код отработал исправно, проверяйте типы данных
shoeseTableAdapter.Insert(
    idshoes, // проверьте тип данных
    textBox_madein.Text, // строка (string)
    textBox_material.Text, // строка (string)
    textBox_size.Text, // строка (string)
    quantity, // целое число (int)
    sex, // проверьте тип данных
    sTwo, // байт (byte)
    price, // целое число (int)
    textBox_model.Text); // строка (string)

Конечно, нужно поставить точку останова и в отладке посмотреть, что у вас хранится в той или иной переменной. Есть предположение, что ошибка кроется в явном преобразовании Convert.ToByte(s2[0]), если нет, то ищите проблему в неявном преобразовании, где возможны ошибки с типом (это места, где я написал «проверьте тип данных»).

Места, с точно такой же ошибкой:

  • Unable to cast object of type ‘System.Windows.Forms.TextBox’ to type ‘System.IConvertible’
  • Unable to cast object of type ‘system.windows.forms.textbox’ to type ‘System.IConvertible’ error
  • Unable to cast object of type ‘system.windows.forms.textbox’ to type ‘System.IConvertible’ error for c# form

Как вы можете заметить, вопрос достаточно популярный, но по своей сути лишь является следствием невнимательности во время написания кода.

И крайний совет, относительно преобразования данных, я бы рекомендовал использовать вместо метода Convert.ToInt32 местод int.TryParse (а также метод Byte.TryParse), лишь по причине того, что метод не упадет с исключением, если не удалось преобразование.

Метод Int32.TryParse (String, Int32) — преобразует строковое
представление числа в эквивалентное ему 32-битовое целое число со
знаком. Возвращает значение, указывающее, успешно ли выполнено
преобразование.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace Lab7._2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            var column1 = new DataGridViewColumn();
            column1.HeaderText = "Значение аргумента";
            column1.Width = 100;
            column1.ReadOnly = true;
            column1.Name = "argument";
            column1.Frozen = true;
            column1.CellTemplate = new DataGridViewTextBoxCell();
            var column2 = new DataGridViewColumn();
            column2.HeaderText = "Значение функции";
            column2.Name = "function";
            column2.CellTemplate = new DataGridViewTextBoxCell();
            var column3 = new DataGridViewColumn();
            column3.HeaderText = "Значение функции класса Math";
            column3.Name = "MathFunction";
            column3.CellTemplate = new DataGridViewTextBoxCell();
            var column4 = new DataGridViewColumn();
            column4.HeaderText = "Разница двух значений";
            column4.Name = "Difference";
            column4.CellTemplate = new DataGridViewTextBoxCell();
            var column5 = new DataGridViewColumn();
            column5.HeaderText = "Количество просуммированных членов ряда";
            column5.Name = "quantity";
            column5.CellTemplate = new DataGridViewTextBoxCell();
            dataGridView1.Columns.Add(column1);
            dataGridView1.Columns.Add(column2);
            dataGridView1.Columns.Add(column3);
            dataGridView1.Columns.Add(column4);
            dataGridView1.Columns.Add(column5);
            dataGridView1.AllowUserToAddRows = false;
            int x1 = Convert.ToInt32(x1TextBox),
                x2 = Convert.ToInt32(x2TextBox),
                dx = Convert.ToInt32(StepTextBox),
                istart;
            double math, func;
            if ((x1 > -1) && (x2 <= 1))
                for (int i = x1; i < x2; i += dx)
                {
                    math = Math.Log(i + 1);
                    func = FuncionWithoutMath(x1, x2, dx);
                    istart = i;
                    dataGridView1.Rows.Add();
                    dataGridView1["argument", dataGridView1.Rows.Count - 1].Value = i;
                    dataGridView1["function", dataGridView1.Rows.Count - 1].Value = func;
                    dataGridView1["MathFunction", dataGridView1.Rows.Count - 1].Value = math;
                    dataGridView1["Difference", dataGridView1.Rows.Count - 1].Value = func - math;
                    dataGridView1["quantity", dataGridView1.Rows.Count - 1].Value = quantityFunc(istart, i, dx);
                }
            else
                Console.WriteLine("Одно из значений х выходит за рамки промежутка");
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    object o = dataGridView1[j, i].Value;
                }
            }
        }
        int FuncionWithoutMath(int start, int end, int step)
        {
            int function = start, n = start, m = 2;
            function += recursia(start+step, end, step, n, m);
            return function;
        }
        int recursia(int start, int end, int step, int n, int m)
        {
            int result = 0;
            if (start < end)
                result = n/m;
            n *= start; m++;
            return result;
        }
        int quantityFunc(int start, int end, int step)
        {
            return (end - start) / step + 1;
        }
    }
}

Понравилась статья? Поделить с друзьями:
  • System sleep wake ошибка mac os
  • System sk carrier ошибка рефрижератора
  • System settings exe системная ошибка в виндовс 10
  • System settings exe ошибка приложения в виндовс 10
  • System service exception ошибка вин 10