Ошибка компилятора cs0029

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

I need convert String of input of table database to Integer value in C# .NET 4 and tried this code inspired from this Link:

    int i;
    string Entry_Level = Convert.ToInt32("2,45");
    i = Convert.ToInt32(Entry_Level); 

But I’ve this error:

Compiler Error Message: CS0029: Cannot implicitly convert type ‘int’ to ‘string’

EDIT

Solved with:

    decimal i;
    string Entry_Level = "2,45";
    i = Convert.ToDecimal(Entry_Level);

    Response.Write(i.ToString());
    Response.End();

In output I’ve 2,45, many thanks!

Mong Zhu's user avatar

Mong Zhu

23.3k10 gold badges44 silver badges76 bronze badges

asked Apr 14, 2014 at 8:49

Chevy Mark Sunderland's user avatar

8

string Entry_Level = Convert.ToInt32("2,45");

should be

string Entry_Level = "2,45";

Why not go for this though:

int i = 2,45;

But since this is not an integer, you’ll need one of the built-in decimal types:

/* use this when precision matters a lot, for example when this is a unit price or a percentage value that will be multiplied with big numbers */
decimal i = 2.45 


/*  use this when precision isn't the most important part. 
It's still really precise, but you can get in trouble when dealing with really small or really big numbers. 
Doubles are fine in most cases.*/
double i = 2.45 

See this thread for more information about decimal vs double.

Community's user avatar

answered Apr 14, 2014 at 8:50

Moeri's user avatar

4

The value 2,45 does not represent an integer. It is a real value. So I believe that you are actually looking for Convert.ToDouble or Convert.ToDecimal. Or perhaps double.Parse or decimal.Parse.

You may also need to consider what happens when you run your code on a machine that does not use , as the decimal separator. Consider using the overloads that accept IFormatProvider.

answered Apr 14, 2014 at 8:53

David Heffernan's user avatar

David HeffernanDavid Heffernan

602k42 gold badges1076 silver badges1491 bronze badges

try this one

string Entry_Level = Convert.ToInt32("2,45").toString()

answered Apr 14, 2014 at 9:02

harits nurrois's user avatar

You can use the line of code below which will remove your compile error but it will through and Runtime Exception cause 2,45 is not a valid integer.

string Entry_Level = Convert.ToInt32("2,45").ToString(); 

I will suggest you to write the below line of codes which will help you to get the value 2.45 on your variable named i

decimal i;
string Entry_Level = "2,45";
Entry_Level = Entry_Level.Replace(',', '.');
i = Convert.ToDecimal(Entry_Level);  

Mong Zhu's user avatar

Mong Zhu

23.3k10 gold badges44 silver badges76 bronze badges

answered Apr 14, 2014 at 9:15

Md.Rajibul Ahsan's user avatar

Archived Forums V

 > 

Visual C# Express Edition

  • Question

  • Question

    Sign in to vote

    0


    Sign in to vote

    Hi,

    I get again an error when i’m trying to excecute this.

    Compiler Error Message: CS0029: Cannot implicitly convert type ‘int’ to ‘string’

    Code Snippet

    int Deelnemer_ID = Convert.ToInt32(Request.QueryString[«Deelnemer_ID»]);
    TextBox2.Text = Deelnemer_ID;

    Thx anyway

    Saturday, April 26, 2008 5:32 PM

Answers

  • Question

    Sign in to vote

    0


    Sign in to vote

    Yeah you implicitly convert an int to a string.  Just add ToString() at the end.
    TextBox2.Text = Deelnemer_ID.ToString();

    Saturday, April 26, 2008 5:36 PM

User-1269234728 posted

Having a Problem running the Code Below.

When I Run The Code Below it throws the following error message:

Compiler Error Message: CS0029: Cannot implicitly convert type ‘string’ to ‘int’

Line 41: int chkBoxChecked; Line 42: int UID;

Line 43: UID = ((Label)(e.Item.FindControl(«lblUID»))).Text;

Line 44: chkBoxChecked = (((CheckBox)(e.Item.FindControl(«edit_DiscontinuedCheckBox»))).Checked) * -1;

Line 45: strSql = «Update ConcertDates Set Discontinued=» + chkBoxChecked + » Where UID=» + UID;

——————————————————————————————————

I’ve already tried the following but still throws error messages:

UID = ((Label)(e.Item.FindControl(«lblUID»))).Int32;

UID = ((Label)(e.Item.FindControl(«lblUID»))).ToInt32;

UID = ((Label)(e.Item.FindControl(«lblUID»)))Convert.Int32;

UID = ((Label)(e.Item.FindControl(«lblUID»))).Int32.Parse;

________________________________________________________

Any Help would be greatly appreciated…Thank You

Below is the Full Code:

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
public class DataGridCheckBox : System.Web.UI.Page
{
 protected System.Web.UI.WebControls.DataGrid dtgConcertDates;
 public string strSql;

 private void Page_Load(object sender, System.EventArgs e)
 {
   if (!(IsPostBack)) {
     BindTheData();
   }
 }

 public void BindTheData()
 {
   SqlConnection objConn = new SqlConnection(ConfigurationSettings.AppSettings[«ConnectionString3»]);
   strSql = «Select Top 10 UID, FullName, Title, ConcertDatesUrl, Discontinued From ConcertDates»;
   SqlCommand objCmd = new SqlCommand(strSql, objConn);
   objConn.Open();
   dtgConcertDates.DataSource = objCmd.ExecuteReader(CommandBehavior.CloseConnection);
   dtgConcertDates.DataBind();
 }

 public void dtgConcertDates_Edit(object sender, DataGridCommandEventArgs e)
 {
   dtgConcertDates.EditItemIndex = e.Item.ItemIndex;
   BindTheData();
 }

 public void dtgConcertDates_Cancel(object sender, DataGridCommandEventArgs e)
 {
   dtgConcertDates.EditItemIndex = -1;
   BindTheData();
 }

public void dtgConcertDates_Update(object sender, DataGridCommandEventArgs e)
{
 int chkBoxChecked;
 int UID;

 UID = ((Label)(e.Item.FindControl(«lblUID»))).Text;


 
chkBoxChecked = (((CheckBox)(e.Item.FindControl(«edit_DiscontinuedCheckBox»))).Checked) * -1;
 strSql = «Update ConcertDates Set Discontinued=» + chkBoxChecked + » Where UID=» + UID;
 SqlConnection objConn = new SqlConnection(ConfigurationSettings.AppSettings[«ConnectionString3»]);
 SqlCommand objCmd = new SqlCommand(strSql, objConn);
 objConn.Open();
 objCmd.ExecuteNonQuery();
 objConn.Close();
 dtgConcertDates.EditItemIndex = -1;
 BindTheData();
}
}

Здраствуйте.
Начну с того что сразу скажу что исправление при помощи
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 дня :(

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка компилятора c3861
  • Ошибка кода 5022 tp link
  • Ошибка компас не прочитан файл содержащий растровое изображение
  • Ошибка компилятора cs0021
  • Ошибка ккт 70c5

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: