2014-07-22 17 views
-3

我有一個在Windows窗體環境需要值的用戶控件,通行證值用戶控件的Windows窗體

  1. 如果我直接加我的用戶控制,我可以看到在我的用戶控制公共變量。
  2. 如果以編程方式添加我的用戶控件,我無法在用戶控件中看到公共變量。

任何人都可以幫我#2嗎?

Code: 
User Control : 
public partial class uctest : UserControl 
    { 
     public DataTable dt1; 
     public int ID; 
       public ucTest() 
     { 
      InitializeComponent(); 
     } 
    } 
////////////////////////////////////////////// 
Form : 

public UserControl ucTest1 =new UC.ucTest(); 

Add User control into tapcontrol: 
tabTest.Controls.Add(this.ucTest1); 

string ID1 = ucTest1.ID; // here is the problem. 
+1

爲什麼你不能看到公共變量?你能展示代碼來證明這個問題嗎?您可以通過設置該對象的屬性值來將值傳遞給對象,這需要構造函數中的值等。聽起來像您試圖設置屬性並且它不起作用,但我們無法幫助您理解*爲什麼*它沒有看到你的嘗試沒有工作。 – David

+0

您需要至少顯示一小段代碼。我不明白你要求什麼。 – LawfulHacker

+0

嗨,夥計們,我用一些代碼HTH更新了這個問題。 – Ihsan

回答

0

爲了查看公共變量,您必須先創建該類的對象。如果你不想創建一個新的對象,那麼你可以將靜態選項添加到公共變量。

例如:

public class TestClass 
{ 
    public string testVar = "I can see you!"; 

    public TestClass() {} 
} 

private class MyForm 
{ 
    TestClass tc = new TestClass(); 
    MessageBox.Show(tc.testVar); 
} 

OR

您可以使用靜態的選擇,對公共變量

public class TestClass 
{ 
    public static string testVar = "I can see you!"; 

    public TestClass() {} 
} 

private class MyForm 
{ 
    MessageBox.Show(TestClass.testVar); 
}