2011-11-14 16 views
0

我正在學習C#Windows窗體應用程序,我一直在努力的一個簡單的應用程序,是提示用戶輸入他們的名字,然後單擊一個按鈕顯示他們在消息框中輸入的內容,並在他們將該字段留空時顯示錯誤消息。我正在使用一個類和方法來處理這個邏輯。 我得到了第一部分的工作,但我無法得到錯誤消息的工作。我考慮過使用if/else,因爲這是我在其他帖子上看到的,但我無法實現。我得到的各種錯誤,目前一個我在課堂上得到的是:我如何得到和如果別人來顯示從一個類MessageBox

錯誤1類型轉換爲「串」的目的,需要

下面是代碼:

// Form1.cs 



using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 

     private void label1_Click(object sender, EventArgs e) 
     { 

     } 

     private void btnDone_Click(object sender, EventArgs e) 
     { 
      string in_name; 


    in_name = Console.ReadLine(); 
     Class1 name = new Class1(); 


     MessageBox.Show(name.GetName("Name: " + inputName.Text)); 
    } 
} 
} 



// Class1.cs 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    class Class1 
    { 
     //Declaring identifiers: 

     string yourName; 


     // Methods 

     public string GetName(string in_name) 
     { 
      if (in_name == null) 
      { 
       MessageBox.Show("You must enter a name"); 
       return; 
      } 
      else 
      { 

       return yourName = in_name; 
      } 
     } 

    } 
} 
+0

這行給出了錯誤? – ChrisF

+0

class文件中的@ChrisF行1 – okr

回答

0

您必須從GetName方法中返回一些東西。

你的方法改成這樣

public string GetName(string in_name) 
{ 
    if (in_name == null) 
    { 
     return "You must enter a name"; 
    } 
    else 
    { 
     return yourName = in_name; 
    } 
} 
+0

我運行它,我沒有得到錯誤,但是該方法繞過了if/else。它顯示messageboc「Name:」。 – okr

+0

檢查編輯。 –

+0

謝謝,我編輯過,但它不斷繞過這個條件(沒有顯示錯誤)。我在我的Class1.cs中的GetName方法中執行此操作 – okr

相關問題