无法将类型'string'隐式转换为'decimal'

时间:2023-01-15 19:19:08
private void button18_Click(object sender, EventArgs e)
    {
        Form1 stForm = new Form1();
        DialogResult result = stForm.ShowDialog(this);

        if (result == DialogResult.Cancel)
            return;
        Inscrierea__pentru_burs_sau_contract media = new Inscrierea__pentru_burs_sau_contract();
        media.Media_MNDP = stForm.MNDP.Text;
        media.Media_MNEA = stForm.MNEA.Text;
        media.Media_Concurs = stForm.MediaConcurs.Text;

        db.Media.Add(media);
        db.SaveChanges();
        MessageBox.Show("Salvarea a avut loc cu succes!!!");
    }

Please help me with my error at line with:

  1. media.Media_MNDP = stForm.MNDP.Text;
  2. media.Media_MNDP = stForm.MNDP.Text;

  3. media.Media_MNEA = stForm.MNEA.Text;
  4. media.Media_MNEA = stForm.MNEA.Text;

  5. media.Media_Concurs = stForm.MediaConcurs.Text;
  6. media.Media_Concurs = stForm.MediaConcurs.Text;

error" Cannot implicitly convert type 'string' to 'decimal'"

错误“无法将类型'字符串'隐式转换为'十进制'”

3 个解决方案

#1


make use of Decimal.TryParse(string, out val)

利用Decimal.TryParse(string,out val)

Example :

decimal val;
if(Decimal.TryParse(stForm.MNDP.Text, out val))
    media.Media_MNDP = val;

better to use tryparse method because it avoid runtime exception to be thrown

最好使用tryparse方法,因为它可以避免抛出运行时异常

#2


Try like this

试试这样吧

 media.Media_MNDP = Decimal.Parse(stForm.MNDP.Text);

For emtpy textbox that will throw error .

对于将抛出错误的emtpy文本框。

To make error free try this

为了使错误免费试试这个

decimal demo;

if(Decimal.TryParse(stForm.MNDP.Text,out demo)){
  media.Media_MNDP = Decimal.Parse(stForm.MNDP.Text);
}

#3


Add try-catch when use Parse

使用Parse时添加try-catch

try{
media.Media_MNDP = Decimal.Parse(stForm.MNDP.Text);
media.Media_MNEA = Decimal.Parse(stForm.MNEA.Text);
media.Media_Concurs = Decimal.Parse(stForm.MediaConcurs.Text);
}
catch(Exception ex){
}

#1


make use of Decimal.TryParse(string, out val)

利用Decimal.TryParse(string,out val)

Example :

decimal val;
if(Decimal.TryParse(stForm.MNDP.Text, out val))
    media.Media_MNDP = val;

better to use tryparse method because it avoid runtime exception to be thrown

最好使用tryparse方法,因为它可以避免抛出运行时异常

#2


Try like this

试试这样吧

 media.Media_MNDP = Decimal.Parse(stForm.MNDP.Text);

For emtpy textbox that will throw error .

对于将抛出错误的emtpy文本框。

To make error free try this

为了使错误免费试试这个

decimal demo;

if(Decimal.TryParse(stForm.MNDP.Text,out demo)){
  media.Media_MNDP = Decimal.Parse(stForm.MNDP.Text);
}

#3


Add try-catch when use Parse

使用Parse时添加try-catch

try{
media.Media_MNDP = Decimal.Parse(stForm.MNDP.Text);
media.Media_MNEA = Decimal.Parse(stForm.MNEA.Text);
media.Media_Concurs = Decimal.Parse(stForm.MediaConcurs.Text);
}
catch(Exception ex){
}