简体   繁体   English

将变量从新表单传递到事件处理程序

[英]Passing a variable from new form to event handler

I want to be able to access my new variable (index) created from another variable(target). 我希望能够访问从另一个变量(目标)创建的新变量(索引)。 I've successfully passed it though from one form to the new form. 我已经成功地将它从一种形式传递给了新形式。 The target variable was chosen by the user choosing a name from a list and then clicking a button. 用户通过从列表中选择一个名称,然后单击一个按钮来选择目标变量。

    public UpdateStudentScores(int target)
    {
        InitializeComponent();
        int index = target;
    }

    private List<Student> students;

    private void UpdateStudentScores_Load(object sender, EventArgs e)
    {

        txtName.Text = students[index].WholeName;
    }

I will be using the new variable(index) as my index to populate the text boxes in the new form. 我将使用新变量(索引)作为索引来填充新表单中的文本框。 I'm not familiar with the event that contains my InitializeComponent(); 我不熟悉包含InitializeComponent()的事件; so I'm not sure how to get that variable out. 所以我不确定如何获取该变量。 Suggestions? 有什么建议吗?

Declare the variable index outside of the constructor. 在构造函数之外声明变量index Then you can set the value of that variable from the constructor and can be used anywhere in that form. 然后,您可以从构造函数中设置该变量的值,并且可以在该表单的任何位置使用它。

int index=0;
public UpdateStudentScores(int target)
{
    InitializeComponent();
    this.index = target;
}

private List<Student> students;

private void UpdateStudentScores_Load(object sender, EventArgs e)
{

    txtName.Text = students[index].WholeName;
}

You can place index variable outside of the constructor. 您可以将index变量放置在构造函数之外。 Make it field or property. 使它成为字段或属性。

int index;
public UpdateStudentScores(int target)
{
    InitializeComponent();
    index = target
}

private List<Student> students;

private void UpdateStudentScores_Load(object sender, EventArgs e)
{

    txtName.Text = students[index].WholeName;
}

全局声明变量“索引”,您将可以访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM