2011-06-20 248 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()

相關問題