开发者

Access form elements

开发者 https://www.devze.com 2022-12-27 05:48 出处:网络
I\'m creating a multiform application in c#. I\'m storing the values from the user in a List in form 1 and I want to access the same stored values of the same list in form 2...I m not able to access t

I'm creating a multiform application in c#. I'm storing the values from the user in a List in form 1 and I want to access the same stored values of the same list in form 2...I m not able to access the stored values...The error I'm getting indicates that there are no values in the list which I'm accessing from form 2...Please help me out...

public Form1() 
{ 
    InitializeCom开发者_如何学编程ponent(); 
} 

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(); 
    }
}


Don't access the Object stored in Form1 from Form2, but pass the Object as a property to Form2.

e.G: Defining the Property:

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

        public Form2()
        {
            InitializeComponent();
        }
    }

Passing the object from form1 to form2:

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


Add a local List variable for your Form2, and a constructor, something like

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

then just pass your List when you create your form 2.

Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消