2011-06-20 77 views
1

我正在学习C#,并且正在使用Visual Studio 2010构建工资计划。我收到一个错误“不能隐式地将类型'int'转换为'short'”。C#错误:无法将类型'int'隐式转换为'short'

我的代码是:

private void btn_add_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       // Get service instance 
       var employerPeriodService = Program.Kernel.Get<IEmployerPeriodService>(); 

       // Get new code 
       var newCode = employerPeriodService.GenerateSAPCode(); 

       // Create object 
       var employerPeriodAdd = 
        new EmployerPeriod 
        { 
         Code = newCode, 
         Name = newCode, 
         U_Tax_year = int.Parse(cb_tax_year.Text), 
         //U_Day_hrs = cb_number_hours.Text, 
         //U_Week_days = cb_number_days_week.Text, 
         //U_Week_hrs = txt_number_hours_week.Text, 
         //U_Month_days = cb_number_days_month.Text, 
         //U_Month_hrs = txt_number_hours_month.Text, 
         //U_Fortnight_days = cb_number_days_fortnight.Text, 
         //U_Fortnight_hrs = txt_number_hours_fortnight.Text, 
         //U_Weeks_in_month = cb_avg_weeks_month.Text, 
         //U_No_of_Fortnights = cb_avg_fortnights_month.Text, 
         U_Starting_period = Convert.ToDateTime(dateTimePicker1.Text), 
         U_Ending_period = Convert.ToDateTime(dateTimePicker2.Text) 

         //U_Comments = txt_comments.Text 
        }; 

       // Save record 
       employerPeriodService.AddEmployerPeriod(employerPeriodAdd); 

       MessageBox.Show("Employer Payroll Period Added Successfully. Intake Ref: " + newCode.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
      } 
      catch (RulesException ex) 
      { 
       MessageBox.Show(ex.GetErrorMessages(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
      } 
     } 

在Microsoft SQL Server在我的数据库,U_Tax_year被定义为SMALLINT。我需要做些什么来解决这个错误。我是否将组合框'cb_tax_year.Text'中的内容转换为int,以及如何实现此功能。

任何帮助表示赞赏。

+0

您是否试过short.Parse而不是int.Parse? –

回答

8

我怀疑这是为改变这一简单:

U_Tax_year = int.Parse(cb_tax_year.Text), 

这样:

U_Tax_year = short.Parse(cb_tax_year.Text), 

基本上你应该检查U_Tax_year属性的类型,并确保适当的分析文本,使=符号的RHS的结果与属性类型是分配兼容的。

+0

谢谢。我以为一个int是int还是long int。解决了。 –

3

使用short.Parse而不是int.Parse

3

的SQLServer的smallint是C#的short相当。所以请尝试short.Parse()而不是int.Parse()

相关问题