POCO, ACE, Loki и другие продвинутые C++ библиотеки
NullReferenced 13.05.2025
В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .
Паттерны проектирования GoF на C#
UnmanagedCoder 13.05.2025
Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .
Создаем CLI приложение на Python с Prompt Toolkit
py-thonny 13.05.2025
Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .
Конвейеры ETL с Apache Airflow и Python
AI_Generated 13.05.2025
ETL-конвейеры – это набор процессов, отвечающих за извлечение данных из различных источников (Extract), их преобразование в нужный формат (Transform) и загрузку в целевое хранилище (Load). . . .
Выполнение асинхронных задач в Python с asyncio
py-thonny 12.05.2025
Современный мир программирования похож на оживлённый мегаполис – тысячи процессов одновременно требуют внимания, ресурсов и времени. В этих джунглях операций возникают ситуации, когда программа. . .
Работа с gRPC сервисами на C#
UnmanagedCoder 12.05.2025
gRPC (Google Remote Procedure Call) — открытый высокопроизводительный RPC-фреймворк, изначально разработанный компанией Google. Он отличается от традиционых REST-сервисов как минимум тем, что. . .
CQRS (Command Query Responsibility Segregation) на Java
Javaican 12.05.2025
CQRS — Command Query Responsibility Segregation, или разделение ответственности команд и запросов. Суть этого архитектурного паттерна проста: операции чтения данных (запросы) отделяются от операций. . .
Шаблоны и приёмы реализации DDD на C#
stackOverflow 12.05.2025
Когда я впервые погрузился в мир Domain-Driven Design, мне показалось, что это очередная модная методология, которая скоро канет в лету. Однако годы практики убедили меня в обратном. DDD — не просто. . .
Исследование рантаймов контейнеров Docker, containerd и rkt
Mr. Docker 11.05.2025
Когда мы говорим о контейнерных рантаймах, мы обсуждаем программные компоненты, отвечающие за исполнение контейнеризованных приложений. Это тот слой, который берет образ контейнера и превращает его в. . .
Micronaut и GraalVM — будущее микросервисов на Java?
Javaican 11.05.2025
Облачные вычисления безжалостно обнажили ахиллесову пяту Java — прожорливость к ресурсам и медлительный старт приложений. Традиционные фреймворки, годами радовавшие корпоративных разработчиков своей. . .
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
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,200
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
When using winform, not the type of «string» implicitly converted to «System.Windows.Forms.TextBox» error.
Have made this mistake twice, I had to take a small notebook him down, or else I’m sorry myself.
If this problem occurs, because winform, the name of a control writtenName 。
Hey, that much it is tears, take down small books, then would not make a mistake.
Intelligent Recommendation
Tuple & quot; dict & set
1.tuple (tuple) defines a tuple of an element tuple = (1,) print(tuple) print(type(tuple)) access to tuple elements #Format: tuple name [subscript], subscript starts from 0 tuple1 = (1,2,3,4) print(tu…
Java method quot
Table of contents 1. Method quot 2. Method quoting symbol Third, the instance method of the reference object Fourth, instance method of reference class Fifth, reference the constructor 1. Method quot …
The applet quot Vant weapp
Official website introduction: https://vant-contrib.gitee.io/vant-weapp/quickstart Be sure to follow the steps! Intersection 1. Install NPM package Perform the command to install the NPM package in th…
The second development control and quot
Direction of first, secondary development 1.1 Add class library 1.2 Add components in the class library 1.3 Add Form to reference and inherit the Text 1.4 Add a ErrorProvider control Write custom logi…
More Recommendation
6. Method quot
6. Method quot When we use Lambda, if there is only one method in the method, there is only one method (including the constructed method), and we can use the method to reference to further simplify th…
Пишу калькулятор на 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 += "+";
}
}
Скрин самого калькулятора:
Заранее спасибо
I have to calculate 3 variables which the method is being called from another class. But before I print the result, I have to convert the int result into predetermined letter of value. But my code isn’t work. I have this error on the code:
CS0029 C# Cannot implicitly convert type ‘string’ to ‘System.Windows.Forms.TextBox’
CS0161 C# »: not all code paths return a value
I’ve tried to convert function into string, but the code still won’t work.
This is the class:
class Nilai
{
public int Calculate(int tugas, int uts, int uas)
{
int final = (tugas + uts + uas) / 3;
return final;
}
}
This is the Form1
:
namespace IP_Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
nilaiHuruf1 = nilaiHuruf();
}
public string nilaiHuruf()
{
int a = Convert.ToInt32(tugas1.Text);
int b = Convert.ToInt32(uts1.Text);
int c = Convert.ToInt32(uas1.Text);
Nilai vnilai = new Nilai();
int hasil = vnilai.Calculate(a, b, c);
if (hasil >= 85)
{
nilaiHuruf1.Text = "A";
return nilaiHuruf1.ToString();
}
else if (hasil >= 80)
{
nilaiHuruf1.Text = "A-";
return nilaiHuruf1.ToString();
}
else if (hasil >= 75)
{
nilaiHuruf1.Text = "B+";
return nilaiHuruf1.ToString();
}
else if (hasil >= 70)
{
nilaiHuruf1.Text = "B";
return nilaiHuruf1.ToString();
}
else if (hasil >= 65)
{
nilaiHuruf1.Text = "B-";
return nilaiHuruf1.ToString();
}
else if (hasil >= 60)
{
nilaiHuruf1.Text = "C+";
return nilaiHuruf1.ToString();
}
else if (hasil >= 55)
{
nilaiHuruf1.Text = "C";
return nilaiHuruf1.ToString();
}
else if (hasil >= 45)
{
nilaiHuruf1.Text = "D";
return nilaiHuruf1.ToString();
}
else if (hasil <= 44.99)
{
nilaiHuruf1.Text = "E";
return nilaiHuruf1.ToString();
}
}
}
}
I expect if I call the method from the Class Nilai to the function nilaiHuruf, then I will get the conversion into letter value. After that, I can call the nilaiHuruf function into the button.
asked Sep 10, 2019 at 9:19
2
First, I suggest to extract method (business logic and UI separation). In your case, the business logics is in Nilai
class:
//TODO: think over making entire class static: static class Nilai
class Nilai {
// static: you don't want "this" here
public static int Calculate(int tugas, int uts, int uas) {
return (tugas + uts + uas) / 3;
}
public static string Mark(int mark) {
if (mark >= 85)
return "A";
else if (mark >= 80)
return "A-";
else if (mark >= 75)
return "B+";
else if (mark >= 70)
return "B";
else if (mark >= 65)
return "B-";
else if (mark >= 60)
return "C+";
else if (mark >= 55)
return "C";
else if (mark >= 45)
return "D";
else
return "E";
}
}
then use it (UI in Form1
)
public string nilaiHuruf() {
int a = Convert.ToInt32(tugas1.Text);
int b = Convert.ToInt32(uts1.Text);
int c = Convert.ToInt32(uas1.Text);
// Since Calculate is static, we don't have to create Nilai instance
string mark = Nilai.Mark(Nilai.Calculate(a, b, c));
nilaiHuruf1.Text = mark; // It's Text property which should be assigned
// We should return mark, say "B+"; not nilaiHuruf1.ToString();
return mark;
}
answered Sep 10, 2019 at 9:43
Dmitry BychenkoDmitry Bychenko
181k20 gold badges163 silver badges216 bronze badges
I think that’s simple. When nilaiHuruf1
is a textbox, you can’t assign directly a string to it — you must set the Text
property of the textbox:
private void button1_Click(object sender, EventArgs e)
{
nilaiHuruf1.Text = nilaiHuruf();
}
Within the nilaiHuruf()
method, return nilaiHuruf1.ToString();
will return the full type name of the textbox — not as you expect the text of the textbox. Use return nilaiHuruf1.Text;
instead. Further ToString()
is a method that every object has.
Update
When the value of nilaiHuruf1.Text
is changed within the method nilaiHuruf()
why would you return that value and set it again to the nilaiHuruf1
textbox? Remove the assignment as follows and everything should work:
private void button1_Click(object sender, EventArgs e)
{
nilaiHuruf();
}
answered Sep 10, 2019 at 9:27
1
try to replace :
return nilaiHuruf1.ToString();
into your if
statement to :
return nilaiHuruf1.Text;
answered Sep 10, 2019 at 11:39
The error Cannot implicitly convert type 'string' to 'System.Windows.Forms.TextBox'
is being raised because you are assigning the returned string from a function to a TextBox directly. You need to change this to use the Text
property — nilaiHuruf1.Text = nilaiHuruf();
The error not all code paths return a value
is being raised because you are not handling all the cases for the int value. In particular, you last else if
. Change it to just else
as you have already covered all other grades.
Ideally, the code should follow SOP and can be simplified to as :
private void button1_Click(object sender, EventArgs e)
{
nilaiHuruf1.Text = nilaiHuruf(Convert.ToInt32(tugas1.Text), Convert.ToInt32(uts1.Text), Convert.ToInt32(uas1.Text));
}
public string nilaiHuruf(int a, int b, int c)
{
string rtn = "";
Nilai vnilai = new Nilai();
int hasil = vnilai.Calculate(a, b, c);
if (hasil >= 85)
{
rtn = "A";
}
else if (hasil >= 80)
{
rtn = "A-";
}
else if (hasil >= 75)
{
rtn = "B+";
}
else if (hasil >= 70)
{
rtn = "B";
}
else if (hasil >= 65)
{
rtn = "B-";
}
else if (hasil >= 60)
{
rtn = "C+";
}
else if (hasil >= 55)
{
rtn = "C";
}
else if (hasil >= 45)
{
rtn = "D";
}
else
{
rtn = "E";
}
return rtn;
}
As the function nilaiHuruf
no longer has a dependency on any values within the form, it may be an option to move it to the Nilai
class depending on the purpose of that class.
answered Sep 10, 2019 at 9:47
KamiKami
19.1k4 gold badges51 silver badges63 bronze badges
1
Exception is your code is not all code paths return value. If you look at your last if, it doesn’t have else. You must return something from all code blocks.
And you just need to return nilaiHuruf1.Text
Alternative solution for you. Works with C# 7 and above.
private void button1_Click(object sender, EventArgs e)
{
nilaiHuruf1.Text = nilaiHuruf();
}
public string nilaiHuruf()
{
int.TryParse(tugas1.Text, out int a);
int.TryParse(uts1.Text, out int b);
int.TryParse(uas1.Text, out int c);
Nilai vnilai = new Nilai();
int hasil = vnilai.Calculate(a, b, c);
string mark = "";
switch (hasil)
{
case int n when (n >= 85):
mark = "A";
break;
case int n when (n >= 80):
mark = "A-";
break;
case int n when (n >= 75):
mark = "B+";
break;
case int n when (n >= 70):
mark = "B";
break;
//// fill other cases
default:
mark = "E";
break;
}
return mark;
}
answered Sep 10, 2019 at 9:50
cdevcdev
5,0432 gold badges33 silver badges32 bronze badges
0 / 0 / 0
Регистрация: 22.03.2021
Сообщений: 64
1
.NET Core
22.04.2021, 21:43. Показов 3469. Ответов 1
Для вывода результатов работы программы, необходимо
использовать метод GetInformation() класса Person, задача которого будет
выводить строку, в которой будет содержаться текущая информация об
экземпляре класса: поля name, age, profession
Помогите, пожалуйста!!!!!!!!!!!!!
Не могу вывести результат. Выдает ошибку » ResultBox += new_person.GetInformation(); »
Пишет, что не удалось неявно преобразовать тип string в System.Windows.Forms.TextBox
Код самой программы:
C# | ||
|
Код класса Person:
C# | ||
|
Миниатюры
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:\users\dell\documents\visual studio 2012\Projects\bmi_calc\bmi_calc\Form1.cs 44 31 bmi_calc
Error 5 Argument 1: cannot convert from 'System.Windows.Forms.TextBox' to 'string' c:\users\dell\documents\visual studio 2012\Projects\bmi_calc\bmi_calc\Form1.cs 45 31 bmi_calc
Error 1 Cannot implicitly convert type 'string' to 'System.Windows.Forms.TextBox' c:\users\dell\documents\visual studio 2012\Projects\bmi_calc\bmi_calc\Form1.cs 39 25 bmi_calc
Error 2 The best overloaded method match for 'double.Parse(string)' has some invalid arguments c:\users\dell\documents\visual studio 2012\Projects\bmi_calc\bmi_calc\Form1.cs 44 17 bmi_calc
Error 4 The best overloaded method match for 'double.Parse(string)' has some invalid arguments c:\users\dell\documents\visual studio 2012\Projects\bmi_calc\bmi_calc\Form1.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.
asked Nov 18, 2016 at 13:19
2
Both txtVisina
and txtTezina
are TextBox
objects, not the strings that are contained within them. You need to use the .Text
property coming off those objects to access the string value within the user interface.
For example:
v = Double.Parse (txtVisina.Text);
t = Double.Parse (txtTezina.Text);
and:
txtBmiRez.Text = "";
Funnily enough, your second usage of txtBmiRez
is actually correct.
When it comes to parsing doubles (or any object from a string), it’s also recommended to handle any potential errors with that which can be done with TryParse
. Parse
would throw an exception if the strings were not valid numbers whereas TryParse
would return false
. For example changing your Click method to something like this is advantageous and would reduce any potential for crashing:
private void button1_Click(object sender, EventArgs e)
{
if(Double.TryParse (txtVisina.Text, out v) &&
Double.TryParse (txtTezina.Text, out t)) {
r = t / (v * v);
txtBmiRez.Text = String.Format("{0:f}", r);
} else {
// Handle failure to parse
MessageBox.Show("Failed to parse text to number.");
}
}
answered Nov 18, 2016 at 13:22
Rudi VisserRudi Visser
21.4k5 gold badges71 silver badges97 bronze badges
2
The variables txtVisina
and txtTezina
are TextBoxes
but you are trying to use them as strings. All you need to use is their Text
property, i.e.
v = Double.Parse (txtVisina.Text);
t = Double.Parse (txtTezina.Text);
answered Nov 18, 2016 at 13:22
TheLethalCoderTheLethalCoder
6,6586 gold badges34 silver badges69 bronze badges
You need to access the Text
property of a TextBox
to get its text. You’re trying to cast the text box itself.
For example, instead of
v = Double.Parse (txtVisina);
the following is correct:
v = Double.Parse (txtVisina.Text);
answered Nov 18, 2016 at 13:22
Thorsten DittmarThorsten Dittmar
56k8 gold badges91 silver badges140 bronze badges
You need to use the Textbox.Text property to get the value entered in to the text box, for example
string enteredValue = textbox1.Text;
Easy mistake to make when you’re starting out with WinForms. I did it a lot!
answered Nov 18, 2016 at 13:22
DrMistryDrMistry
3211 silver badge13 bronze badges
for the Errors 3 and 5 you must use .Text property for the TextBoxes.
To assign any string to a textbox you must use following syntax:
textboxid.Text=»»;
and if you want to assign any non string value to it then use:.ToString() function to convert a variable to string before assigning it to textbox.
eg
int i=10;
Textbox1.Text=i.ToString();
answered Nov 18, 2016 at 13:31
Мне нужно вычислить 3 переменные, метод которых вызывается из другого класса. Но прежде чем я напечатаю результат, я должен преобразовать результат int в заранее определенную букву значения. Но мой код не работает. У меня ошибка в коде:
CS0029 C# Невозможно неявно преобразовать строку типа в System.Windows.Forms.TextBox CS0161 C#: не все пути кода возвращают значение
Я пытался преобразовать функцию в строку, но код все равно не работает.
Это класс:
class Nilai
{
public int Calculate(int tugas, int uts, int uas)
{
int final = (tugas + uts + uas) / 3;
return final;
}
}
Это Form1
:
namespace IP_Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
nilaiHuruf1 = nilaiHuruf();
}
public string nilaiHuruf()
{
int a = Convert.ToInt32(tugas1.Text);
int b = Convert.ToInt32(uts1.Text);
int c = Convert.ToInt32(uas1.Text);
Nilai vnilai = new Nilai();
int hasil = vnilai.Calculate(a, b, c);
if (hasil >= 85)
{
nilaiHuruf1.Text = "A";
return nilaiHuruf1.ToString();
}
else if (hasil >= 80)
{
nilaiHuruf1.Text = "A-";
return nilaiHuruf1.ToString();
}
else if (hasil >= 75)
{
nilaiHuruf1.Text = "B+";
return nilaiHuruf1.ToString();
}
else if (hasil >= 70)
{
nilaiHuruf1.Text = "B";
return nilaiHuruf1.ToString();
}
else if (hasil >= 65)
{
nilaiHuruf1.Text = "B-";
return nilaiHuruf1.ToString();
}
else if (hasil >= 60)
{
nilaiHuruf1.Text = "C+";
return nilaiHuruf1.ToString();
}
else if (hasil >= 55)
{
nilaiHuruf1.Text = "C";
return nilaiHuruf1.ToString();
}
else if (hasil >= 45)
{
nilaiHuruf1.Text = "D";
return nilaiHuruf1.ToString();
}
else if (hasil <= 44.99)
{
nilaiHuruf1.Text = "E";
return nilaiHuruf1.ToString();
}
}
}
}
Я ожидаю, что если я вызову метод из класса Nilai в функцию nilaiHuruf, я получу преобразование в буквенное значение. После этого я могу вызвать функцию nilaiHuruf в кнопке.
2019-09-10 12:19
5
ответов
Во-первых, я предлагаю извлечь метод (бизнес-логику и разделение пользовательского интерфейса). В вашем случае бизнес-логика находится вNilai
учебный класс:
//TODO: think over making entire class static: static class Nilai
class Nilai {
// static: you don't want "this" here
public static int Calculate(int tugas, int uts, int uas) {
return (tugas + uts + uas) / 3;
}
public static string Mark(int mark) {
if (mark >= 85)
return "A";
else if (mark >= 80)
return "A-";
else if (mark >= 75)
return "B+";
else if (mark >= 70)
return "B";
else if (mark >= 65)
return "B-";
else if (mark >= 60)
return "C+";
else if (mark >= 55)
return "C";
else if (mark >= 45)
return "D";
else
return "E";
}
}
затем используйте его (пользовательский интерфейс в Form1
)
public string nilaiHuruf() {
int a = Convert.ToInt32(tugas1.Text);
int b = Convert.ToInt32(uts1.Text);
int c = Convert.ToInt32(uas1.Text);
// Since Calculate is static, we don't have to create Nilai instance
string mark = Nilai.Mark(Nilai.Calculate(a, b, c));
nilaiHuruf1.Text = mark; // It's Text property which should be assigned
// We should return mark, say "B+"; not nilaiHuruf1.ToString();
return mark;
}
2019-09-10 12:43
Попробуйте заменить:
return nilaiHuruf1.ToString();
в ваш if
заявление на:
return nilaiHuruf1.Text;
2019-09-10 14:39
Я думаю, это просто. когдаnilaiHuruf1
является текстовым полем, вы не можете напрямую присвоить ему строку — вы должны установить Text
свойство текстового поля:
private void button1_Click(object sender, EventArgs e)
{
nilaiHuruf1.Text = nilaiHuruf();
}
В рамках nilaiHuruf()
метод return nilaiHuruf1.ToString();
вернет полное имя типа текстового поля, а не то, что вы ожидаете от текстового поля. Использоватьreturn nilaiHuruf1.Text;
вместо. В дальнейшемToString()
это метод, который есть у каждого объекта.
Обновить
Когда значение nilaiHuruf1.Text
изменяется внутри метода nilaiHuruf()
зачем вам вернуть это значение и снова установить его на nilaiHuruf1
текстовое окно? Удалите назначение следующим образом, и все должно работать:
private void button1_Click(object sender, EventArgs e)
{
nilaiHuruf();
}
2019-09-10 12:27
Исключением является то, что ваш код не возвращает значение всех путей кода. Если вы посмотрите на свое последнее «если», то другого у него нет. Вы должны вернуть что-то из всех блоков кода.
И тебе просто нужно вернуться nilaiHuruf1.Text
Альтернативное решение для вас. Работает с C# 7 и выше.
private void button1_Click(object sender, EventArgs e)
{
nilaiHuruf1.Text = nilaiHuruf();
}
public string nilaiHuruf()
{
int.TryParse(tugas1.Text, out int a);
int.TryParse(uts1.Text, out int b);
int.TryParse(uas1.Text, out int c);
Nilai vnilai = new Nilai();
int hasil = vnilai.Calculate(a, b, c);
string mark = "";
switch (hasil)
{
case int n when (n >= 85):
mark = "A";
break;
case int n when (n >= 80):
mark = "A-";
break;
case int n when (n >= 75):
mark = "B+";
break;
case int n when (n >= 70):
mark = "B";
break;
//// fill other cases
default:
mark = "E";
break;
}
return mark;
}
2019-09-10 12:50
Ошибка Cannot implicitly convert type 'string' to 'System.Windows.Forms.TextBox'
возникает, потому что вы назначаете возвращаемую строку из функции непосредственно TextBox. Вам нужно изменить это, чтобы использоватьText
свойство — nilaiHuruf1.Text = nilaiHuruf();
Ошибка not all code paths return a value
возникает, потому что вы не обрабатываете все случаи для значения int. В частности, вы последнийelse if
. Измените его на простоelse
поскольку вы уже прошли все остальные оценки.
В идеале код должен соответствовать СОП и может быть упрощен до следующего вида:
private void button1_Click(object sender, EventArgs e)
{
nilaiHuruf1.Text = nilaiHuruf(Convert.ToInt32(tugas1.Text), Convert.ToInt32(uts1.Text), Convert.ToInt32(uas1.Text));
}
public string nilaiHuruf(int a, int b, int c)
{
string rtn = "";
Nilai vnilai = new Nilai();
int hasil = vnilai.Calculate(a, b, c);
if (hasil >= 85)
{
rtn = "A";
}
else if (hasil >= 80)
{
rtn = "A-";
}
else if (hasil >= 75)
{
rtn = "B+";
}
else if (hasil >= 70)
{
rtn = "B";
}
else if (hasil >= 65)
{
rtn = "B-";
}
else if (hasil >= 60)
{
rtn = "C+";
}
else if (hasil >= 55)
{
rtn = "C";
}
else if (hasil >= 45)
{
rtn = "D";
}
else
{
rtn = "E";
}
return rtn;
}
Поскольку функция nilaiHuruf
больше не зависит от каких-либо значений в форме, это может быть возможность переместить его в Nilai
класс в зависимости от цели этого класса.
2019-09-10 12:47
Другие вопросы по тегам
c#
Во время разработки приложений на платформе .NET, особенно при работе с пользовательским интерфейсом, может возникнуть ошибка «Не удается неявно преобразовать тип «string» в «System.Windows.Forms.TextBox».» Эта ошибка указывает на то, что код пытается преобразовать значение типа «string» в тип «TextBox», который является элементом управления для ввода текста в Windows Forms.
Прежде чем разобраться, как исправить эту ошибку, важно понять, почему она возникает. Обычно ошибка возникает, когда программист пытается присвоить значение типа «string» переменной типа «TextBox». Например, вот такой код может вызвать эту ошибку:
string myString = "Пример текста";
TextBox myTextBox = myString;
В данном примере происходит попытка присвоить значение переменной типа «string» (myString
) переменной типа «TextBox» (myTextBox
). Однако, такое преобразование типов не может быть выполнено неявно, так как это разные типы данных.
Для исправления этой ошибки можно воспользоваться явным преобразованием типов. В случае с примером выше, это можно сделать следующим образом:
string myString = "Пример текста";
TextBox myTextBox = new TextBox();
myTextBox.Text = myString;
Здесь мы создаем новый экземпляр класса «TextBox» с помощью оператора new
. Затем, используя свойство Text
, мы присваиваем переменной myTextBox
значение переменной myString
. При этом явное преобразование типов не требуется, так как оба значения имеют тип «string».
Кроме того, данная ошибка может возникнуть при использовании методов или свойств, которые ожидают параметр типа «TextBox», но получают значение типа «string». В этом случае, мы также можем использовать явное преобразование типов, чтобы исправить ошибку. Например:
public void SetTextBoxValue(TextBox textBox, string value)
{
textBox.Text = value;
}
// Пример вызова метода
string myString = "Пример текста";
TextBox myTextBox = new TextBox();
SetTextBoxValue(myTextBox, myString);
Здесь мы создаем метод SetTextBoxValue
, который принимает параметры textBox
типа «TextBox» и value
типа «string». Внутри метода мы используем свойство Text
элемента управления «textBox», чтобы присвоить ему значение value
.
В заключение, ошибка «Не удается неявно преобразовать тип «string» в «System.Windows.Forms.TextBox».» возникает при попытке преобразовать значение типа «string» в тип «TextBox» без использования явного преобразования типов. Для исправления этой ошибки можно создать новый экземпляр класса «TextBox» и присвоить ему значение типа «string», либо явно преобразовать типы при вызове методов или свойств, ожидающих параметры типа «TextBox».
- Где можно скачать игру Feed The Panda, на компьютер?
- Нужно ли утоптывать чувство, давно закопанное в прошлом, или оно рано или поздно все равно вырвется наружу?
- Пропал поиск музыки. Теперь ни одну песню нельзя найти. Это временный сбой, или это специально так сделали?
- Бороться и искать — найти и перепрятать?
- Подскажите, где установлена сигнализация на ВАЗ 2123? Утопила брелок сигнализации. Помогите…
- Как избавиться от привычки тревожиться по поводу и без?
- Где купить часы?
- Любила ли я?
Другие наши интересноые статьи: