Не удается неявно преобразовать тип string в system windows forms textbox

I don't know what to do because the error is in the Form1.Designer.cs and because I have no experience in debugging that part of the program. //Form1 // this.AutoScaleDimensions = new System.Draw...

I don’t know what to do because the error is in the Form1.Designer.cs and because I have no experience in debugging that part of the program.

//Form1
// 
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(352, 246);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Generate Username";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);

Abbas's user avatar

Abbas

14k6 gold badges41 silver badges71 bronze badges

asked Jan 29, 2014 at 14:49

YellowSubmarine's user avatar

YellowSubmarineYellowSubmarine

1511 gold badge4 silver badges13 bronze badges

9

The error is on this.Name = «Form1»;

I suspect you have created a control named Name, which conflicts with the Name property of the window. Just rename the control to something else and it should work again.

answered Jan 29, 2014 at 14:52

Thomas Levesque's user avatar

Thomas LevesqueThomas Levesque

284k66 gold badges617 silver badges751 bronze badges

1

The error must come from somewhere else, there’s nothing here with a TextBox. The error is probably caused by assigning a string to a TextBox itself instead of assigning a string to the Text property of the TextBox.

Example:

TextBox tb = new TextBox();
tb = "Default text";

This should be:

TextBox tb = new TextBox();
tb.Text = "Default text";

Otherwise you have created a control with a name like Name or Text, in which case you’ll have to rename it to NameTextBox or something.

answered Jan 29, 2014 at 14:53

Abbas's user avatar

0

0 / 0 / 0

Регистрация: 22.03.2021

Сообщений: 64

1

.NET Core

22.04.2021, 21:43. Показов 2609. Ответов 1


Для вывода результатов работы программы, необходимо
использовать метод GetInformation() класса Person, задача которого будет
выводить строку, в которой будет содержаться текущая информация об
экземпляре класса: поля name, age, profession

Помогите, пожалуйста!!!!!!!!!!!!!
Не могу вывести результат. Выдает ошибку » ResultBox += new_person.GetInformation(); »
Пишет, что не удалось неявно преобразовать тип string в System.Windows.Forms.TextBox

Код самой программы:

C#
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
99
100
101
102
103
104
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 Приложение_ср3_пробное
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void label1_Click(object sender, EventArgs e)
        {
 
        }
 
        private void groupBox1_Enter(object sender, EventArgs e)
        {
 
        }
 
        private void label2_Click(object sender, EventArgs e)
        {
 
        }
 
        private void label3_Click(object sender, EventArgs e)
        {
 
        }
 
        private void NameBox_TextChanged(object sender, EventArgs e)
        {
            
 
            
        }
 
        private void AgeBox_TextChanged(object sender, EventArgs e)
        {
 
        }
 
        private void ProfessionBox_TextChanged(object sender, EventArgs e)
        {
 
        }
        
 
        private void StartButton_Click(object sender, EventArgs e)
        {
            Person new_person;
            if (NameBox.Text == "")
            {
                MessageBox.Show("Введите имя");
            }
 
            if (AgeBox.Text != "")
            {
                if (ProfessionBox.Text != "")
                {
                    new_person = new Person(NameBox.Text, Convert.ToInt32(AgeBox.Text), ProfessionBox.Text);
                }
                else
                {
                    new_person = new Person(NameBox.Text, Convert.ToInt32(AgeBox.Text));
                }
            }
            else
            {
                if (ProfessionBox.Text != "")
                {
 
                    new_person = new Person(NameBox.Text, 0, ProfessionBox.Text);
                }
                else
                {
                    new_person = new Person(NameBox.Text);
                }
 
 
            }
            ResultBox += new_person.GetInformation();
 
 
        }
        
        private void ResultBox_TextChanged(object sender, EventArgs e)
        {
            
        }
 
       
    }
    
}

Код класса Person:

C#
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
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Приложение_ср3_пробное
{
    class Person
    {
        string name;
        int age;
        string profession;
 
        public Person(string name)
        {
            this.name = name;
        }
 
        public Person(string name, int age)
        {
            this.name = name;
            this.age = age;
        }
        public Person(string name, string profession)
        {
            this.name = name;
            this.profession = profession;
        }
        public Person(string name, int age, string profession)
        {
            this.name = name;
            this.age = age;
            this.profession = profession;
        }
        public string GetInformation()
        {
            string information;
            information = " Имя: " + this.name + "; Возраст: " + this.age.ToString() + " ; Профессия: " + this.profession;
            return information;
            
        }
        
 
    }
    
}

Миниатюры

Не удалось неявно преобразовать тип string в System.Windows.Forms.TextBox
 

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



I’m building very basic BMI Calculator in C# and Win Forms using VS 2012, also I’m quite new to C#. I’m followed some examples and this code should work, but when run code, I’m getting those errors.

Error   3   Argument 1: cannot convert from 'System.Windows.Forms.TextBox' to 'string'  c:usersdelldocumentsvisual studio 2012Projectsbmi_calcbmi_calcForm1.cs  44  31  bmi_calc
Error   5   Argument 1: cannot convert from 'System.Windows.Forms.TextBox' to 'string'  c:usersdelldocumentsvisual studio 2012Projectsbmi_calcbmi_calcForm1.cs  45  31  bmi_calc
Error   1   Cannot implicitly convert type 'string' to 'System.Windows.Forms.TextBox'   c:usersdelldocumentsvisual studio 2012Projectsbmi_calcbmi_calcForm1.cs  39  25  bmi_calc
Error   2   The best overloaded method match for 'double.Parse(string)' has some invalid arguments  c:usersdelldocumentsvisual studio 2012Projectsbmi_calcbmi_calcForm1.cs  44  17  bmi_calc
Error   4   The best overloaded method match for 'double.Parse(string)' has some invalid arguments  c:usersdelldocumentsvisual studio 2012Projectsbmi_calcbmi_calcForm1.cs  45  17  bmi_calc

Here is my code:

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 bmi_calc
{
    public partial class Form1 : Form
    {
        double v;
        double t;
        double r;


        public Form1()
        {
            InitializeComponent();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            txtTezina.Clear(); //Btn that resets height and weight field values.
            txtVisina.Clear();
            txtBmiRez = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            v = Double.Parse (txtVisina);
            t = Double.Parse (txtTezina);

            r = t / (v * v);

            txtBmiRez.Text = String.Format("{0:f}", r);

        }

        private void button3_Click(object sender, EventArgs e)
        {
            Application.Exit(); // Close app
        }

    }
}

If someone could explain me this, I would be eternally grateful.

I’m building very basic BMI Calculator in C# and Win Forms using VS 2012, also I’m quite new to C#. I’m followed some examples and this code should work, but when run code, I’m getting those errors.

Error   3   Argument 1: cannot convert from 'System.Windows.Forms.TextBox' to 'string'  c:usersdelldocumentsvisual studio 2012Projectsbmi_calcbmi_calcForm1.cs  44  31  bmi_calc
Error   5   Argument 1: cannot convert from 'System.Windows.Forms.TextBox' to 'string'  c:usersdelldocumentsvisual studio 2012Projectsbmi_calcbmi_calcForm1.cs  45  31  bmi_calc
Error   1   Cannot implicitly convert type 'string' to 'System.Windows.Forms.TextBox'   c:usersdelldocumentsvisual studio 2012Projectsbmi_calcbmi_calcForm1.cs  39  25  bmi_calc
Error   2   The best overloaded method match for 'double.Parse(string)' has some invalid arguments  c:usersdelldocumentsvisual studio 2012Projectsbmi_calcbmi_calcForm1.cs  44  17  bmi_calc
Error   4   The best overloaded method match for 'double.Parse(string)' has some invalid arguments  c:usersdelldocumentsvisual studio 2012Projectsbmi_calcbmi_calcForm1.cs  45  17  bmi_calc

Here is my code:

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 bmi_calc
{
    public partial class Form1 : Form
    {
        double v;
        double t;
        double r;


        public Form1()
        {
            InitializeComponent();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            txtTezina.Clear(); //Btn that resets height and weight field values.
            txtVisina.Clear();
            txtBmiRez = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            v = Double.Parse (txtVisina);
            t = Double.Parse (txtTezina);

            r = t / (v * v);

            txtBmiRez.Text = String.Format("{0:f}", r);

        }

        private void button3_Click(object sender, EventArgs e)
        {
            Application.Exit(); // Close app
        }

    }
}

If someone could explain me this, I would be eternally grateful.

Вопрос:

Моя форма с именем form2.vb имеет этот код.

Private Sub ADDRESS_TICKETDataGridView_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles ADDRESS_TICKETDataGridView.CellDoubleClick
Dim value As String = ADDRESS_TICKETDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString()
If e.ColumnIndex = e.ColumnIndex Then
Search.Show()
Search.TextBox1 = value



End If
End Sub
End Class

Но по ошибке мне кажется, что значение типа “String” не может быть преобразовано в “System.Windows.Forms.TextBox”. Я хочу исправить эту проблему, по сути, хочу, чтобы получить значение из datagridview и ввести его в другую форму с текстовым полем. Может ли это быть сделано, или я делаю что-то неправильно. Пожалуйста помоги?

Лучший ответ:

Search.TextBox1 = value

Вы просто попытались назначить переменную TextBox1 для хранения строки вместо текстового поля.

Это не имеет никакого смысла.

Вместо этого вы хотите установить текст, отображаемый в текстовом поле, установив его свойство Text.

Ответ №1

Просто для информации (и для добавления в мой комментарий к Slacks answer), есть способ приблизиться к этому поведению, используя перегрузку операторов. (Код находится на С#, но я предполагаю, что он легко переводится в VB.Net)

Просто создайте класс, наследующий TextBox следующим образом:

public class MyTextBox : TextBox
{
public static implicit operator string(MyTextBox t)
{
return t.Text;
}

public static implicit operator MyTextBox(string s)
{
MyTextBox tb = new MyTextBox();
tb.Text = s;
return tb;
}

public static MyTextBox operator +(MyTextBox tb1, MyTextBox tb2)
{
tb1.Text += tb2.Text;
return tb1;
}
}

И тогда вы сможете делать такие вещи:

MyTextBox tb = new MyTextBox();
tb.Text = "Hello ";
tb += "World";

Тогда содержимое вашего текстового поля будет Hello World

Я попытался заставить его работать с tb = "test", но не удалось.

When developing a .NET application (i.e. in C#), under certain circumstances, you might get the error message: Cannot implicitly convert type ‘string’ to ‘System.Windows.Forms.DataGridViewTextBoxColumn

Example of Exception in Visual Studio when Using the Reserved Word "Name" as a DataGridView Column Name - SQLNetHub Article

Example of Exception in Visual Studio when Using the Reserved Word “Name” as a DataGridView Column Name.

Why you got the implicit conversion error

If you get the above error, then you have most probably set as a column name for one of your datagridview column the reserved word ‘name‘.

If you do this, then the compiler finds a conflict between the assignment of the form’s name and the DataGridview’s column name.


Get Started with .NET Programming Fast and Easy!

Check our online course titled “.NET Programming for Beginners – Windows Forms with C#.
(special limited-time discount included in link).

.NET Programming for Beginners: Windows Forms (C#) - Online Course

Learn how to implement Windows Forms projects in .NET using Visual Studio and C#, how to implement multithreading, how to create deployment packages and installers for your .NET Windows Forms apps using ClickOnce in Visual Studio, and more! 

Many live demonstrations and downloadable resources included!

Enroll from $14.99


How to resolve the issue

To resolve this issue just change the name of the DataGridView’s column to something else instead of “name”.

There is a reason there are reserved words not only in .NET byut in many other development platforms as well (i.e. SQL Server, etc.).

To this end, please make sure that you are not using any reserved words in your development work because if you use them, there is always the risk of a conflict with system routines like the above example.

Check this MSDN article for information about the words reserved by the linker.

Featured Online Courses:

  • Introduction to Azure Database for MySQL
  • Working with Python on Windows and SQL Server Databases
  • Boost SQL Server Database Performance with In-Memory OLTP
  • Introduction to Azure SQL Database for Beginners
  • Essential SQL Server Administration Tips
  • SQL Server Fundamentals – SQL Database for Beginners
  • Essential SQL Server Development Tips for SQL Developers
  • Introduction to Computer Programming for Beginners
  • .NET Programming for Beginners – Windows Forms with C#
  • SQL Server 2019: What’s New – New and Enhanced Features
  • Entity Framework: Getting Started – Complete Beginners Guide
  • How to Import and Export Data in SQL Server Databases
  • A Guide on How to Start and Monetize a Successful Blog

Artemakis Artemiou

Artemakis Artemiou is a Senior SQL Server Architect, Author, a 9 Times Microsoft Data Platform MVP (2009-2018). He has over 20 years of experience in the IT industry in various roles. Artemakis is the founder of SQLNetHub and {essentialDevTips.com}. Artemakis is the creator of the well-known software tools Snippets Generator and DBA Security Advisor. Also, he is the author of many eBooks on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA). Moreover, Artemakis teaches on Udemy, you can check his courses here.

Views: 7,958

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit «Cookie Settings» to provide a controlled consent. Read More

Я не знаю, что делать, потому что ошибка находится в Form1.Designer.cs и потому, что у меня нет опыта в отладке этой части программы.

//Form1
// 
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(352, 246);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Generate Username";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);

29 янв. 2014, в 16:45

Поделиться

Источник

2 ответа

Ошибка на этом .Name = «Form1»;

Я подозреваю, что вы создали элемент управления с именем Name, который конфликтует с свойством Name окна. Просто переименуйте элемент управления в другое, и он снова должен работать.

Thomas Levesque
29 янв. 2014, в 16:46

Поделиться

Ошибка должна произойти откуда-то еще, здесь нет ничего с TextBox. Вероятно, ошибка вызвана назначением строки самому TextBox вместо назначения строки свойству Text TextBox.

Пример:

TextBox tb = new TextBox();
tb = "Default text";

Это должно быть:

TextBox tb = new TextBox();
tb.Text = "Default text";

В противном случае вы создали элемент управления с именем типа Name или Text, и в этом случае вам придется переименовать его в NameTextBox или что-то еще.

Abbas
29 янв. 2014, в 15:21

Поделиться

Ещё вопросы

  • 0Перенаправление на определенную веб-страницу после того, как пользователи выбирают из выпадающего меню форму и php
  • 1Как я могу отложить предупреждение и перезагрузить, чтобы аудио файл мог воспроизводиться в javascript?
  • 0Разбор строки массива массива строк обратно в массив
  • 1Разделить список объектов
  • 1Удаление всевозможных лишних пробелов между предложением и абзацем
  • 1Aurelia диалог повторной проверки
  • 0Cordova InAppBrowser показать адресную строку Cordova AngularJS Oauth
  • 0Получить среднее значение значений строк каждого месяца и сгруппированных по пользователю
  • 0Как автоматически загрузить изображение на сервер, используя Javascript
  • 1Невозможно получить доступ к функции внутри функции JavaScript
  • 1FileIO из ArrayList
  • 0Сортировка массивов PHP и проблема экспорта файлов
  • 0Динамическое изменение атрибута ui-sref в ui-router
  • 1C # Запустить новый процесс MailTo и кодирование URL-адреса HTML
  • 1Что-то не так с моей панелью таймера
  • 1Сортировка панд df по отдельным столбцам
  • 0HTML не полностью жидкий
  • 1добавить элемент в конце списка связанных ссылок [закрыт]
  • 0PHP / MySQL категории сообщений
  • 1Добавление оператора else в пары значений ключа словаря Javascript?
  • 0Использование двухмерных массивов в качестве параметров
  • 1Значение типа «Стиль» нельзя добавить в коллекцию или словарь типа «UIElementCollection».
  • 0Как заменить статические переменные динамическими для каждого цикла в функции
  • 0изменить отображаемое имя ячейки в выводе sql запроса
  • 1Вопрос макета — как начать действие, не перемещая определенные элементы интерфейса?
  • 3google.auth.exceptions.DefaultCredentialsError:
  • 1Google Cloud Datastore Индексы для запросов количества
  • 0Поле ввода имеет поле по умолчанию
  • 0Где написать скрипт jQuery на странице ASP.NET?
  • 0После символической ссылки: ОШИБКА 2002 (HY000): Не удается подключиться к локальному серверу MySQL через сокет ‘/tmp/mysql.sock’ (2)
  • 1Совместное использование кода между приложениями
  • 1Применить функцию, возвращающую одномерный массив ко всем элементам массива numpy
  • 1Как управлять действиями в Android?
  • 0Показывать окно оповещения, когда пользователь выбирает неприемлемый файл в плагине danialfarid / ng-file-upload
  • 1.toLocaleString в движке Nashorn
  • 0Ошибки Sendgrid x-smtpapi с «отсутствующим адресом электронной почты»
  • 0Переменная, переданная = в область видимости, не обязательна
  • 0OpenGL переключение между орто и перспективой
  • 0php — mysql — обновление приложений и баз данных через tfs
  • 1Динамическая маршрутизация с использованием колбы и Python не работает
  • 1Я получаю исключение NullPointerException при попытке использовать учебник Eclipse «Hello World»
  • 1Может ли процесс Android разместить несколько виртуальных машин Dalvik?
  • 1Как перевести ячейку в режим редактирования, как только она получит фокус
  • 0Вызов базового метода Zurb Foundation 4 содержит код, конфликтующий с Prototype.js
  • 1Как отобразить предупреждение без фона и заголовка приложения?
  • 1Класс C # Деинициализация динамической памяти
  • 1mp3transform | Воспроизведение (mp3) в отдельной теме
  • 1Чтобы проверить определенный формат в текстовом поле
  • 1Свойство ‘do’ не существует для типа ‘Подписка’
  • 0Как смоделировать команду curl с Angular

Сообщество Overcoder

Пишу калькулятор на C# WinForms.
Принцип действия таков:
При нажатии на кнопку с цифрой или мат.опирацией она отображается в текстбоксе
При нажатии «=» текст в текстбоке переводится в Double и выводится туда же
Проблема: CS0029 Не удается неявно преобразовать тип «double» в «System.Windows.Forms.TextBox».
Код кнопки «=»:

private void button13_Click(object sender, EventArgs e)
        {
                textBox1 = Convert.ToDouble(textBox1.Text);  
        }

До этого возникала такая проблема с кнопками других мат.оперций, с ней я справился с помощью

if (textBox1 != null)
            {
                textBox1.Text += "+";
            }

Но с «=» так не проходит
Код кнопок мат.операций, если нужно:

private void button8_Click(object sender, EventArgs e)
        {
            if (textBox1 != null)
            {
                textBox1.Text += "-";
            }
        }

        private void button12_Click(object sender, EventArgs e)
        {
            if (textBox1 != null)
            {
                textBox1.Text += "+";
            }
        }

Скрин самого калькулятора:
627ac3fd9f604168460542.png
Заранее спасибо

Понравилась статья? Поделить с друзьями:
  • Не удается неявно преобразовать тип string в system windows forms label
  • Не удается неявно преобразовать тип string в system windows forms datagridviewtextboxcolumn
  • Не удается настроить обновления windows отмена изменений не выключайте компьютер
  • Не удается настроить обновления windows 7 выполняется отмена изменений
  • Не удается настроить мобильный хот спот на windows 10 на ноутбуке