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

Ошибка при сборке: Неявное преобразование типа 'string' в 'System.Windows.Forms.DataGridViewTextBoxColumn' C# Решение и ответ на вопрос 1259872

yarkov_aleksei

0 / 0 / 3

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

Сообщений: 93

1

21.09.2014, 04:07. Показов 14175. Ответов 4

Метки нет (Все метки)


Работаю в SharpDevelop 4.4. При сборке проекта вылазит ошибка:
«Неявное преобразование типа ‘string’ в ‘System.Windows.Forms.DataGridViewTextBoxColumn’ невозможно (CS0029)»
Ругается на эту строчку:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.AdressDataGridView);
this.Controls.Add(this.toolStrip1);
this.MaximizeBox = false;
 
this.Name = "ContactForm";  // <---
 
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.AdressDataGridView)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();

Переименовал форму и понеслось. Обратное переименование ничего не дало. Весь моск сломал уже.

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



0



25 / 19 / 7

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

Сообщений: 1,354

21.09.2014, 13:19

2

Поставь Visual Studio хотя-бы 10, и не парься.



0



0 / 0 / 0

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

Сообщений: 25

18.12.2015, 10:00

3

Pin1999, Стоит 12 студия. Ошибка точно такая же и вылазит у меня впервые. С чем это может быть связанно и как это исправить? Делал как обычно, добавил форму, закинул datagrid и понеслось. На время, пока работал с функцией, удалил из дизайнера формы строку this.Name=»…»; , но теперь мне нужно имя формы, а задать его нельзя, с ним не компилится =(



0



11 / 11 / 1

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

Сообщений: 2

13.04.2016, 13:03

4

Лучший ответ Сообщение было отмечено Ev_Hyper как решение

Решение

100% Сюда кто-то да зайдёт. Решение такое: У вас в datagridview рабочее имя одного из столбцов Name и вижла (в моём случае) ассоциирует его с полем Datagridview и ругается. Поменяйте рабочее имя колонки



11



0 / 0 / 0

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

Сообщений: 27

21.04.2016, 21:38

5

megagem, спасибо Вам большое! верно говорят, всё гениальное просто)



0



I have tried below solutions for that but still its giving me same error :
Cannot implicitly convert type ‘string’ to ‘System.Windows.Forms.TextBox’

Here is my code of form elements :

 private void InitializeComponent()
{
         this.Controls.Add(this.splitContainer1);
            this.ImeMode = System.Windows.Forms.ImeMode.On;
            this.Name = "UserForm"; // Here I have a problem while runing the application
            this.Text = "User Log Management";
}

I have tried to change the name of Form but still its not working.

Here is the Snap for code :
Here is the Snap for code
Thanks

asked Jun 22, 2017 at 13:50

Laxman Gite's user avatar

Laxman GiteLaxman Gite

2,1882 gold badges15 silver badges23 bronze badges

4

One of the text boxes in your form has an ID of «Name». Rename it to «txtName» and your code should work fine

answered Jun 22, 2017 at 13:54

praty's user avatar

pratypraty

5252 silver badges9 bronze badges

1

You have a TextBox control on your form that you have called Name. That is causing a conflict. Rename your text box to something distinct. A common convention in WinForms development is to use control prefixes (or suffixes). For example txt for text boxes. e.g. txtName.

See here for further discussion on naming.

answered Jun 22, 2017 at 13:55

DavidG's user avatar

DavidGDavidG

110k12 gold badges215 silver badges212 bronze badges

0

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

According to the top answer on this Stackoverflow question, the following code should be in the correct format. Yet, it produces a build error that says, «Cannot implicitly convert type ‘string’ to ‘System.Windows.Forms.DataGridViewTextBoxColumn’.»

   dataGridView1.Rows.Add(new Object[]{Int32.Parse(text[i+j*5+1]), text[i+j*5+2], total});

I get the exact same error when I try the format suggested by the top answer to this Stackoverflow question.

   dataGridView1.Rows.Add(new DataGridViewRow());
   dataGridView1.Rows[dataGridView1.RowCount-1].Cells[dataGridView1.Columns["Number"].Index].Value = Int32.Parse(text[i+j*5+1]);
   dataGridView1.Rows[dataGridView1.RowCount-1].Cells[dataGridView1.Columns["Name"].Index].Value = text[i+j*5+2];
   dataGridView1.Rows[dataGridView1.RowCount-1].Cells[dataGridView1.Columns["Total"].Index].Value = total;

EDIT – the error actually appears to be on a completely different page of my project. I haven’t even opened this page before now; so I have no idea how the error could be here. For some reason, the following line in Form1.Designer.cs is the culprit.

   this.Name = "Form1";

EDIT II – okay so, I changed the name of the second column of my DataGridView from «Name» to «NameFull» on a hunch; and the build error is no longer produced. So I guess I’ve solved my own problem. However, I’m very curious to know how that happened. Why would the name of a DataGridView column conflict with the name property of the containing form?

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.

Dmitry Bychenko's user avatar

asked Sep 10, 2019 at 9:19

Jericho's user avatar

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 Bychenko's user avatar

Dmitry BychenkoDmitry Bychenko

174k18 gold badges160 silver badges206 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

CodeTherapist's user avatar

1

try to replace :

return nilaiHuruf1.ToString();

into your if statement to :

return nilaiHuruf1.Text;

Dmitry Bychenko's user avatar

answered Sep 10, 2019 at 11:39

Poula Ashraf's user avatar

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

Kami's user avatar

KamiKami

19k4 gold badges49 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

cdev's user avatar

cdevcdev

4,7872 gold badges31 silver badges32 bronze badges

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.

Dmitry Bychenko's user avatar

asked Sep 10, 2019 at 9:19

Jericho's user avatar

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 Bychenko's user avatar

Dmitry BychenkoDmitry Bychenko

174k18 gold badges160 silver badges206 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

CodeTherapist's user avatar

1

try to replace :

return nilaiHuruf1.ToString();

into your if statement to :

return nilaiHuruf1.Text;

Dmitry Bychenko's user avatar

answered Sep 10, 2019 at 11:39

Poula Ashraf's user avatar

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

Kami's user avatar

KamiKami

19k4 gold badges49 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

cdev's user avatar

cdevcdev

4,7872 gold badges31 silver badges32 bronze badges

Содержание

  1. Не удается преобразовать из «string» в «System.Windows.Forms.TextBox»
  2. Data Grid View Text Box Column Класс
  3. Определение
  4. Примеры
  5. Комментарии
  6. Примечания для тех, кто наследует этот метод
  7. Конструкторы
  8. Свойства
  9. Методы
  10. События

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

Здравствуйте! Кто-нибудь знает как исправить эту ошибку: Не удается преобразовать из «string» в «System.Windows.Forms.TextBox»

Ошибка возникает в функции:

Не удается неявно преобразовать тип «string» в «System.Windows.Forms.DataGridViewTextBoxColumn»
Привет, Работал работал в результате вот что появилось убрать не могу никак Ошибка такая.

Как исправить ошибку «Не удается преобразовать из «System.Windows.Forms.TextBox» в «bool»?
Функция: Proxy.Set(new WebProxy(«ip адрес», порт)); Хочу сделать что бы данные выводились из.

Как исправить ошибку ‘Не удается неявно преобразовать тип «System.Collections.Generic.IEnumerable » в «string»‘?
Не удается неявно преобразовать тип «System.Collections.Generic.IEnumerable » в «string». .

Рядовой, здравствуйте! Я переписал функцию так и сообщение исчезло:

Рядовой, спасибо за ссылку. Я применил ее к своему коду, но не знаю как сделать, чтобы считалось на каждом шаге: ввожу, например 2, нажимаю «+», и снова ввожу два, затем нажимаю любую из операций получаю 4, затем снова ввожу число и получаю общий результат. Вы можете помочь добиться такой функциональности?

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Неявное преобразование типа «int» в «System.Windows.Forms.TextBox» невозможно
Помогите! Я новичок в C#. Хочу сделать переводчик. Вот код. using System; using.

Неявное преобразование типа «int» в «System.Windows.Forms.TextBox» невозможно
Работаю понятное дело в Win Forms Подумал сделать небольшую калькуляционную программу, но вот.

Data Grid View Text Box Column Класс

Определение

Размещает коллекцию ячеек DataGridViewTextBoxCell. Hosts a collection of DataGridViewTextBoxCell cells.

Примеры

В следующем примере кода показано использование этого типа. The following code example illustrates the use of this type.

Комментарии

DataGridViewTextBoxColumnКласс является специализированным типом DataGridViewColumn класса, который используется для логического размещения ячеек, позволяющих отображать и изменять текстовые строки. The DataGridViewTextBoxColumn class is a specialized type of DataGridViewColumn class used to logically host cells that enable displaying and editing of text strings. DataGridViewTextBoxColumnУ объекта есть связанный DataGridViewTextBoxCell объект, каждый из DataGridViewRow которых пересекает его. A DataGridViewTextBoxColumn has an associated DataGridViewTextBoxCell object in every DataGridViewRow that intersects it. Когда DataGridViewTextBoxCell активируется, он предоставляет DataGridViewTextBoxEditingControl элемент управления для выполнения ввода данных пользователем. When a DataGridViewTextBoxCell becomes activated, it supplies a DataGridViewTextBoxEditingControl control to handle user input.

По умолчанию для этого типа столбца используется режим сортировки Automatic . The sort mode for this column type defaults to Automatic.

Примечания для тех, кто наследует этот метод

При наследовании от DataGridViewTextBoxColumn и добавлении новых свойств в производный класс обязательно Переопределите Clone() метод, чтобы скопировать новые свойства во время операций клонирования. When you derive from DataGridViewTextBoxColumn and add new properties to the derived class, be sure to override the Clone() method to copy the new properties during cloning operations. Также следует вызвать метод базового класса, Clone() чтобы свойства базового класса копировались в новую ячейку. You should also call the base class’s Clone() method so that the properties of the base class are copied to the new cell.

Конструкторы

Инициализирует новый экземпляр класса DataGridViewTextBoxColumn, устанавливая его в состояние по умолчанию. Initializes a new instance of the DataGridViewTextBoxColumn class to the default state.

Свойства

Возвращает или задает режим, в котором автоматически изменяется ширина столбца. Gets or sets the mode by which the column automatically adjusts its width.

(Унаследовано от DataGridViewColumn) CellTemplate

Получает или задает шаблон, используемый для моделирования внешнего вида ячеек. Gets or sets the template used to model cell appearance.

Возвращает тип времени выполнения шаблона ячеек. Gets the run-time type of the cell template.

(Унаследовано от DataGridViewColumn) ContextMenuStrip

Возвращает или задает контекстное меню для столбца. Gets or sets the shortcut menu for the column.

(Унаследовано от DataGridViewColumn) DataGridView

Получает элемент управления DataGridView, связанный с данным элементом. Gets the DataGridView control associated with this element.

(Унаследовано от DataGridViewElement) DataPropertyName

Возвращает или задает имя того свойства данных или столбца базы данных в источнике данных, с которым связан столбец DataGridViewColumn. Gets or sets the name of the data source property or database column to which the DataGridViewColumn is bound.

(Унаследовано от DataGridViewColumn) DefaultCellStyle

Возвращает или задает стиль по умолчанию для ячеек столбца. Gets or sets the column’s default cell style.

(Унаследовано от DataGridViewColumn) DefaultHeaderCellType

Получает или задает тип времени выполнения для ячейки заголовка по умолчанию. Gets or sets the run-time type of the default header cell.

(Унаследовано от DataGridViewBand) Displayed

Получает значение, показывающее, отображается ли диапазон на экране в данный момент. Gets a value indicating whether the band is currently displayed onscreen.

(Унаследовано от DataGridViewBand) DisplayIndex

Возвращает или задает расположение столбца относительно столбцов, отображаемых в текущий момент. Gets or sets the display order of the column relative to the currently displayed columns.

(Унаследовано от DataGridViewColumn) DividerWidth

Возвращает или задает ширину (в пикселях) разделителя столбца. Gets or sets the width, in pixels, of the column divider.

(Унаследовано от DataGridViewColumn) FillWeight

Возвращает или задает значение, представляющее ширину столбца, находящегося в режиме заполнения, относительно ширины других столбцов элемента управления, находящихся в этом режиме. Gets or sets a value that represents the width of the column when it is in fill mode relative to the widths of other fill-mode columns in the control.

(Унаследовано от DataGridViewColumn)

Frozen

Возвращает или задает значение, указывающее, перемещается ли столбец, когда пользователь выполняет горизонтальную прокрутку элемента управления DataGridView. Gets or sets a value indicating whether a column will move when a user scrolls the DataGridView control horizontally.

(Унаследовано от DataGridViewColumn) HasDefaultCellStyle

Получает значение, показывающее, было ли установлено свойство DefaultCellStyle. Gets a value indicating whether the DefaultCellStyle property has been set.

(Унаследовано от DataGridViewBand) HeaderCell

Возвращает или задает объект DataGridViewColumnHeaderCell, представляющий заголовок столбца. Gets or sets the DataGridViewColumnHeaderCell that represents the column header.

(Унаследовано от DataGridViewColumn) HeaderCellCore

Получает или задает ячейку заголовка объекта DataGridViewBand. Gets or sets the header cell of the DataGridViewBand.

(Унаследовано от DataGridViewBand) HeaderText

Возвращает или задает текст ячейки заголовка столбца. Gets or sets the caption text on the column’s header cell.

(Унаследовано от DataGridViewColumn) Index

Получает относительную позицию диапазона в элементе управления DataGridView. Gets the relative position of the band within the DataGridView control.

(Унаследовано от DataGridViewBand) InheritedAutoSizeMode

Возвращает или задает режим изменения размера, действующий для столбца. Gets the sizing mode in effect for the column.

(Унаследовано от DataGridViewColumn) InheritedStyle

Возвращает стиль ячейки, применяемый в текущий момент к столбцу. Gets the cell style currently applied to the column.

(Унаследовано от DataGridViewColumn) IsDataBound

Возвращает значение, указывающее, связан ли столбец с источником данных. Gets a value indicating whether the column is bound to a data source.

(Унаследовано от DataGridViewColumn) IsRow

Получает значение, показывающее, представляет ли диапазон строку. Gets a value indicating whether the band represents a row.

(Унаследовано от DataGridViewBand) MaxInputLength

Получает или задает наибольшее количество символов, которое можно ввести в данное текстовое поле. Gets or sets the maximum number of characters that can be entered into the text box.

Возвращает или задает наименьшую ширину столбца (в пикселях). Gets or sets the minimum width, in pixels, of the column.

(Унаследовано от DataGridViewColumn) Name

Возвращает или задает имя столбца. Gets or sets the name of the column.

(Унаследовано от DataGridViewColumn) ReadOnly

Возвращает или задает значение, указывающее, может ли пользователь изменять ячейки столбца. Gets or sets a value indicating whether the user can edit the column’s cells.

(Унаследовано от DataGridViewColumn) Resizable

Возвращает или задает значение, указывающее, возможно ли изменение размера столбца. Gets or sets a value indicating whether the column is resizable.

(Унаследовано от DataGridViewColumn) Selected

Получает или задает значение, показывающее, выделен ли диапазон в пользовательском интерфейсе. Gets or sets a value indicating whether the band is in a selected user interface (UI) state.

(Унаследовано от DataGridViewBand) Site

Возвращает или задает подложку столбца. Gets or sets the site of the column.

(Унаследовано от DataGridViewColumn) SortMode

Возвращает или задает режим сортировки для столбца. Gets or sets the sort mode for the column.

Получает состояние пользовательского интерфейса для элемента. Gets the user interface (UI) state of the element.

(Унаследовано от DataGridViewElement) Tag

Получает или задает объект, содержащий данные, связанные с диапазоном. Gets or sets the object that contains data to associate with the band.

(Унаследовано от DataGridViewBand) ToolTipText

Возвращает или задает текст, используемый для подсказок. Gets or sets the text used for ToolTips.

(Унаследовано от DataGridViewColumn) ValueType

Возвращает или задает тип данных для значений в ячейках столбца. Gets or sets the data type of the values in the column’s cells.

(Унаследовано от DataGridViewColumn) Visible

Возвращает или задает значение, показывающее, видим ли столбец. Gets or sets a value indicating whether the column is visible.

(Унаследовано от DataGridViewColumn) Width

Возвращает или задает текущую ширину столбца. Gets or sets the current width of the column.

(Унаследовано от DataGridViewColumn)

Методы

Создает точную копию данного диапазона. Creates an exact copy of this band.

(Унаследовано от DataGridViewColumn) Dispose()

Освобождает все ресурсы, занятые модулем DataGridViewBand. Releases all resources used by the DataGridViewBand.

(Унаследовано от DataGridViewBand) Dispose(Boolean)

Освобождает неуправляемые ресурсы, используемые объектом DataGridViewBand, а при необходимости освобождает также управляемые ресурсы. Releases the unmanaged resources used by the DataGridViewBand and optionally releases the managed resources.

(Унаследовано от DataGridViewColumn) Equals(Object)

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) GetHashCode()

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetPreferredWidth(DataGridViewAutoSizeColumnMode, Boolean)

Вычисляет оптимальную ширину столбца на основе указанных критериев. Calculates the ideal width of the column based on the specified criteria.

(Унаследовано от DataGridViewColumn) GetType()

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) MemberwiseClone()

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) OnDataGridViewChanged()

Вызывается, когда диапазон связан с другим элементом управления DataGridView. Called when the band is associated with a different DataGridView.

(Унаследовано от DataGridViewBand) RaiseCellClick(DataGridViewCellEventArgs)

Вызывает событие CellClick. Raises the CellClick event.

(Унаследовано от DataGridViewElement) RaiseCellContentClick(DataGridViewCellEventArgs)

Вызывает событие CellContentClick. Raises the CellContentClick event.

(Унаследовано от DataGridViewElement) RaiseCellContentDoubleClick(DataGridViewCellEventArgs)

(Унаследовано от DataGridViewElement) RaiseCellValueChanged(DataGridViewCellEventArgs)

Вызывает событие CellValueChanged. Raises the CellValueChanged event.

(Унаследовано от DataGridViewElement) RaiseDataError(DataGridViewDataErrorEventArgs)

Вызывает событие DataError. Raises the DataError event.

(Унаследовано от DataGridViewElement) RaiseMouseWheel(MouseEventArgs)

Вызывает событие MouseWheel. Raises the MouseWheel event.

(Унаследовано от DataGridViewElement) ToString()

Возвращает строку, описывающую столбец. Gets a string that describes the column.

События

Происходит при удалении объекта DataGridViewColumn. Occurs when the DataGridViewColumn is disposed.

  • Remove From My Forums
  • Question

  • Hello guys!

    I’m really stuck at this point of creating a dynamic datagridview with 2 columns, i used the datgridtextboxcolumns but i keep getting this error «cannot implicitly convert type system.windows.forms.datagridtextboxcolumn to system.windows.forms.datagridviewcolumn»
    for «dgviewcol1» and «dgviewcol2» when i try to add new columns with AddRange. i also have the error saying that the Visible property doesn’t exist in datagridviewtextboxcolumn which is false.

    Anyone know how can i get rid of this errors?? Much appreciated!

    code:

     private DataGridView dgview;
            private DataGridTextBoxColumn dgviewcol1;
            private DataGridTextBoxColumn dgviewcol2;
            void Search()
            {
                dgview = new DataGridView();
                dgviewcol1 = new DataGridTextBoxColumn();
                dgviewcol2 = new DataGridTextBoxColumn();
                this.dgview.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
                this.dgview.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {this.dgviewcol1, this.dgviewcol2}); // «cannot implicitly convert type system.windows.forms.datagridtextboxcolumn to system.windows.forms.datagridviewcolumn»
                dataGridView2.Visible = false;
                this.dgviewcol1.Visible = false; // Visible property doesn’t exist in datagridviewtextboxcolumn
                this.dgviewcol2.Visible = false;
                this.Controls.Add(dgview);
                this.dgview.ReadOnly = true;
                dgview.BringToFront();

            }

  • Remove From My Forums
  • Question

  • Hello guys!

    I’m really stuck at this point of creating a dynamic datagridview with 2 columns, i used the datgridtextboxcolumns but i keep getting this error «cannot implicitly convert type system.windows.forms.datagridtextboxcolumn to system.windows.forms.datagridviewcolumn»
    for «dgviewcol1» and «dgviewcol2» when i try to add new columns with AddRange. i also have the error saying that the Visible property doesn’t exist in datagridviewtextboxcolumn which is false.

    Anyone know how can i get rid of this errors?? Much appreciated!

    code:

     private DataGridView dgview;
            private DataGridTextBoxColumn dgviewcol1;
            private DataGridTextBoxColumn dgviewcol2;
            void Search()
            {
                dgview = new DataGridView();
                dgviewcol1 = new DataGridTextBoxColumn();
                dgviewcol2 = new DataGridTextBoxColumn();
                this.dgview.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
                this.dgview.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {this.dgviewcol1, this.dgviewcol2}); // «cannot implicitly convert type system.windows.forms.datagridtextboxcolumn to system.windows.forms.datagridviewcolumn»
                dataGridView2.Visible = false;
                this.dgviewcol1.Visible = false; // Visible property doesn’t exist in datagridviewtextboxcolumn
                this.dgviewcol2.Visible = false;
                this.Controls.Add(dgview);
                this.dgview.ReadOnly = true;
                dgview.BringToFront();

            }

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