2015-03-13 108 views
-1

我的問題很簡單。我想單擊Form1中的一個面板,這將導致userControl1中的label1,它將放置在form2上以更改爲「文本」。C#更改usercontrol labeltext和背景顏色

單擊此面板也會更改所述userControl1的背景顏色。我收到錯誤"'TileInterFaceTest.Usercontrol1.label1' due to its protection level",坦率地讓我感到困惑。

即使單獨運行顏色更改代碼,它也無法達到預期結果。

要說清楚,當談到C#和編程時,我是一個新手。直到現在我一直在使用Visual Basic,所以類,方法和對象的概念對我來說有點困惑。

這裏是我的Form1代碼:

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

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 


     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void panel1_Click(object sender, EventArgs e) 
     { 
      Form2 form2 = new Form2(); 
      UserControl1 userControl1 = new UserControl1(); 
      form2.Show(); 
      userControl1.BackColor = System.Drawing.Color.Red; 
      userControl1.LabelText = "Text"; 

     } 

     private void panel1_Paint(object sender, PaintEventArgs e) 
     { 

     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 
    } 
} 

代碼的UserControl1:

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

namespace WindowsFormsApplication1 
{ 
    public partial class UserControl1 : UserControl 
    { 
     public String LabelText 
     { 
      get 
      { 
       return label1.Text; 
      } 
      set 
      { 
       label1.Text = value; 
      } 
     } 

     public UserControl1() 
     { 

      InitializeComponent(); 
     } 

     private void UserControl1_Load(object sender, EventArgs e) 
     { 

     } 
    } 
} 
+0

也應該從生成的默認值中重新命名你的變量。 – JNYRanger 2015-03-13 22:41:21

+0

我只是想要一些可行的東西。在確定如何實際使程序執行期望的結果之後,我將適當地重命名該變量。但現在看來似乎沒有必要。 – ShreddedWheat 2015-03-13 22:59:12

+0

我不同意。如果你只是使用生成的代碼,當然。一旦開始編寫「代碼隱藏」(例如事件處理程序),就可以使用專有名稱。 – JNYRanger 2015-03-13 23:01:06

回答

2

label1private場,這意味着你不能訪問它的類UserControl1之外。

你可以做的是在類UserControl1的定義添加一個公共財產:

public String LabelText { 
    get { 
     return label1.Text; 
    } 
    set { 
     label1.Text = value; 
    } 
} 

然後使用該屬性修改label1文本的價值:

private void panel1_Click(object sender, EventArgs e) 
{ 
    form2.Show(); 
    userControl1.BackColor = System.Drawing.Color.Red; 
    userControl1.LabelText = "Text"; 
} 
+0

感謝您的回覆。但這是我第二次使用完全相同的解決方案,而且我似乎沒有得到任何結果。有什麼我可能做錯了類或對象的定義? – ShreddedWheat 2015-03-13 22:28:27

+0

編輯您的問題併發布您正在使用的代碼。沒有看到代碼,我們無法幫助你。 – Otiel 2015-03-13 22:31:12

+0

爲Form1和UserControl1添加了代碼。我確信我錯過了一些非常明顯的事情。我感謝你的耐心。 – ShreddedWheat 2015-03-13 22:38:26