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

What does this mean?
Im using windows form, and heres my code so far, Please help!

double number1;
            double number2;
            double result;

            number1 = double.Parse(textBox1.Text);
            number2 = double.Parse(textBox2.Text);

            result = Math.Sqrt((number1 * number1) + (number2 * number2));

            label1 = result.ToString();

Answers (4)

Распределенное обучение с TensorFlow и Python

AI_Generated 05.05.2025

В машинном обучении размер имеет значение. С ростом сложности моделей и объема данных одиночный процессор или даже мощная видеокарта уже не справляются с задачей обучения за разумное время. Когда. . .

CRUD API на C# и GraphQL

stackOverflow 05.05.2025

В бэкенд-разработке постоянно возникают новые технологии, призванные решить актуальные проблемы и упростить жизнь программистам. Одной из таких технологий стал GraphQL — язык запросов для API,. . .

Распознавание голоса и речи на C#

UnmanagedCoder 05.05.2025

Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .

Реализация своих итераторов в C++

NullReferenced 05.05.2025

Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .

Разработка собственного фреймворка для тестирования в C#

UnmanagedCoder 04.05.2025

C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .

Распределенная трассировка в Java с помощью OpenTelemetry

Javaican 04.05.2025

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

Шаблоны обнаружения сервисов в Kubernetes

Mr. Docker 04.05.2025

Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .

Создаем SPA на C# и Blazor

stackOverflow 04.05.2025

Мир веб-разработки за последние десять лет претерпел коллосальные изменения. Переход от традиционных многостраничных сайтов к одностраничным приложениям (Single Page Applications, SPA) — это. . .

Реализация шаблонов проектирования GoF на C++

NullReferenced 04.05.2025

«Банда четырёх» (Gang of Four или GoF) — Эрих Гамма, Ричард Хелм, Ральф Джонсон и Джон Влиссидес — в 1994 году сформировали канон шаблонов, который выдержал проверку временем. И хотя C++ претерпел. . .

C# и сети: Сокеты, gRPC и SignalR

UnmanagedCoder 04.05.2025

Сетевые технологии не стоят на месте, а вместе с ними эволюционируют и инструменты разработки. В . NET появилось множество решений — от низкоуровневых сокетов, позволяющих управлять каждым байтом. . .

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).

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!

Learn More


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.

Recommended Online Courses:

  • AI Essentials: A Beginner’s Guide to Artificial Intelligence
  • SQL Server 2022: What’s New – New and Enhanced Features
  • Working with Python on Windows and SQL Server Databases
  • Introduction to Azure Database for MySQL
  • 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
  • Data Management for Beginners – Main Principles
  • A Guide on How to Start and Monetize a Successful Blog

Artemakis Artemiou is a seasoned Senior Database and AI/Automation Architect with over 20 years of expertise in the IT industry. As a Certified Database, Cloud, and AI professional, he has been recognized as a thought leader, earning the prestigious Microsoft Data Platform MVP title for nine consecutive years (2009-2018). Driven by a passion for simplifying complex topics, Artemakis shares his expertise through articles, online courses, and speaking engagements. He empowers professionals around the globe to excel in Databases, Cloud, AI, Automation, and Software Development. Committed to innovation and education, Artemakis strives to make technology accessible and impactful for everyone.

Views: 11,176

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

Здраствуйте.
Начну с того что сразу скажу что исправление при помощи
throw new NotImplementedException();
которое предлагает VS Code не подойдёт тк при использовании combobox поментально кидает к ошибке…

Form1.cs:

using static SDM_Lab5.PasMove;

namespace SDM_Lab5
{
    public partial class Form1 : Form
    {
        Aeroplane aero;
        Train tr;
        Avto av;
        public Form1()
        {
            InitializeComponent();

        }
        PasMove pm;
        
        Gorod[] towns; 
        string pathString = @"C:\Users\Miste\Desktop\Задания_СИ(шарп)\Лабораторные\ЛР_5\SDM_Lab5\SDM_Lab5\img";

        private void Form1_Load(object sender, EventArgs e)
        {
            aero = new Aeroplane(); // создаем экземпляры классов с начальными значениями
            tr = new Train();
            av = new Avto();
            towns = new Gorod[5]; // Задаем значения полей 
            towns[0] = new Gorod("Москва", 709, "Moscow.jpg");
            towns[1] = new Gorod("Рим", 3016, "Rome.jpg");
            towns[2] = new Gorod("Нью-Йорк", 6883, "New-york.jpg");
            towns[3] = new Gorod("Токио", 7598, "Tokyo.jpg");
            towns[4] = new Gorod("Лондон", 2818, "London.jpg");

            
            //  добавим поле Name из каждого объекта в выпадающий список          
            for (int i = 0; i < 5; i++)
            { comboBox1.Items.Add(towns[i].Name); }

        }
        int k;
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            k = comboBox1.SelectedIndex;
            // выводим расстояние до нужного города
            label1.Text = towns[k].ToString();
            // выводим соответствующую картинку          
            pictureBox1.Image = Image.FromFile(pathString + "\\" + towns[k].Url);

        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (comboBox2.Text == "")
            { MessageBox.Show("Не выбран транспорт!"); return; }
            Form2 frm2 = new Form2(pm);
            frm2.ShowDialog();
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comboBox2.SelectedIndex)
            {
                case 0: pm = aero; break; // Ошибки здесь, у aero; tr; av
                case 1: pm = tr; break;
                case 2: pm = av; break;
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (comboBox1.Text == "" || comboBox2.Text == "")
            { MessageBox.Show("Не выбраны данные для расчета"); return; }
            else
            {
                double g = pm.Time(towns[k].Rast);
                double c = (pm.Equals(av)) ? pm.CostTrip(towns[k].Rast) : pm.CostTrip(g);
                label1.Text = string.Format("Стоимость поездки на 1 человека {0:f2} (без учета прочих сборов)", c);
            }

        }
    }
}

PasMove.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SDM_Lab5
{
    public class PasMove
    {
       
        public virtual int CountPas { get; set; }
        public virtual double Speed { get; set; }
        public string Name { get; set; }
        public double CostFuel { get; set; }
        public double Rashod { get; set; }
        public double Time(double s)
        { return s / Speed; }
        public virtual double CostTrip(double t)
        { return t * Rashod * CostFuel / CountPas; }

        public class Aeroplane
        {
            int countPas;
            double speed;

            public int CountPas
            {
                get { return countPas; }
                set { if (value <= 300) countPas = value; }
            }
            public double Speed
            {
                get => speed;
                set { if (value > 600 && value <= 900) speed = value; }
            }
            string Name;
            double CostFuel;
            double Rashod;
            public Aeroplane()
            {
                Name = "Самолет";
                CountPas = 280;
                Speed = 800;
                CostFuel = 37.2;
                Rashod = 2600;
            }

        }
        public class Train
        {
            int countPas;
            double speed;

            public int CountPas
            {
                get { return countPas; }
                set { if (value <= 300) countPas = value; }
            }
            public double Speed
            {
                get => speed;
                set { if (value > 600 && value <= 900) speed = value; }
            }
            string Name;
            double CostFuel;
            double Rashod;
            public Train()
            {
                Name = "Поезд";
                CountPas = 500;
                Speed = 80;
                CostFuel = 3.2;
                Rashod = 1600;

            }

        }
        public class Avto
        {
            int countPas;
            double speed;

            public int CountPas
            {
                get { return countPas; }
                set { if (value <= 300) countPas = value; }
            }
            public double Speed
            {
                get => speed;
                set { if (value > 600 && value <= 900) speed = value; }
            }
            double CostFuel;
            double Rashod;

            public virtual double CostTrip(double t) { return t / 100 * Rashod * CostFuel / CountPas;}
            string Name;
            public  Avto()
            {
                
                Name = "Автомобиль";
                CountPas = 3;
                Speed = 110;
                CostFuel = 3.2;
                Rashod = 1600;

            }
        }
    }
}

628cc57c46943979581608.png

Извините что всё так конкретно и всё сразу не могу найти решение уже 2 дня :(

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Freelancer как запустить на windows 10
  • Нет папки etc windows 10
  • Пропал rdp windows 10
  • Kaspersky endpoint security windows vista
  • Как импортировать драйвера в образ windows 10