2010-04-20 132 views
0

我在c#中創建一個多形式的應用程序。我將用戶的值存儲在表單1中的列表中,我想訪問表單2中相同列表的相同存儲值...我無法訪問存儲的值...錯誤I' m到處表明,有列表中沒有價值,我正在從形式2訪問...請幫我...訪問表單元素

public Form1() 
{ 
    InitializeComponent(); 
} 

public List<string> sub = new List<string>(); 
public int clickcounter = 1; 

public void additems() 
{ 
    sub.Add("Java"); 
    sub.Add("Web Technology"); 
    sub.Add("Software Engineering"); 
    sub.Add("Networks"); 
    sub.Add("ADO.net"); 
} 

public void show() 
{ 
    int x = 10; 
    int y = 10; 
    int m = sub.Count; 

    for (int i = 0; i < m; i++) 
    { 
     string name = "txtBox_" + (i + 1).ToString("00"); 
     TextBox txt = new TextBox(); 
     txt.Name = name; 
     this.Controls.Add(txt); 
     txt.Text = sub[i]; 
     txt.ReadOnly = true; 
     y += 20; 
     txt.Location = new Point(x, y); 
     txt.Width = 120; 
    } 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    if (clickcounter == 1) 
    { 
     additems(); 
     show(); 
    } 
} 
+1

你能分享一些代碼嗎? – rahul 2010-04-20 04:32:41

+0

public Form1() { InitializeComponent(); } public list sub = new List (); public int clickcounter = 1; public void additems() { sub.Add(「Java」); sub.Add(「Web Technology」); sub.Add(「軟件工程」); sub.Add(「Networks」); sub.Add(「ADO.net」); } – Shiv 2010-04-20 04:40:15

+0

public void show() { int x = 10; int y = 10; int m = sub.Count; (int i = 0; i Shiv 2010-04-20 04:41:48

回答

0

不要訪問從Form2的存儲在Form1的對象,但通該對象作爲Form2的一個屬性。

例如: 定義屬性:

public partial class Form2 : Form 
    { 
     public List<String> PersonNames { get; set; } 

     public Form2() 
     { 
      InitializeComponent(); 
     } 
    } 

從Form1中傳遞對象到窗體2:

private void button1_Click(object sender, EventArgs e) 
{ 
     List<String> PersonNames = new List<String>() { "Harald", "Thomas", "Markus" }; 
     ObjektBinaerSerialisieren form2 = new ObjektBinaerSerialisieren(); 
     form2.PersonNames = PersonNames; 
} 
0

添加本地列表變量爲你的窗體2和一個構造函數,像

Public List<String> locaList; 
public form2(List aList) 
{ 
    InitializeComponent(); 
    localList = aList; 
} 

然後只是通過您的名單當您創建您的表單2.

希望幫助。