如何从C#中的不同方法访问变量?

时间:2016-12-19 02:25:03

标签: c# asp.net

如何在page_load上访问变量并在c#中的ddlApp_SelectedIndexChanged方法中使用它? 谢谢

private void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ddlRole.SelectedIndex = 0;
    }

    string ddl = ddlApp.Value.ToString();
    string ddlRoleDs;
    string ddlMenuDs;
    string GvDs;

    if (ddl == "ATTD")
    {
        ddlRoleDs = "ddlAttdDs";
        ddlMenuDs = "ddlMenuAttdDs";
        GvDs = "AttdMenuAssignmentDs";                
    }
    else if (ddl == "TRVL")
    {
        ddlRoleDs = "ddlTrvldDs";
        ddlMenuDs = "ddlMenuTrvlDs";
        GvDs = "TrvlMenuAssignmentDs";                
    }

}

变量:ddlRoleDs,GvDs和ddMenuDs

protected void ddlApp_SelectedIndexChanged(object sender, EventArgs e)
{        
    ddlRole.DataSourceID = ddlRoleDs;
    MenuAssignmentGv.DataSourceID = GvDs;
    ddlMenu.DataSourceID = ddlMenuDs;
}

1 个答案:

答案 0 :(得分:0)

您可以在班级中使用私人全球会员。这样他们只能在课堂上访问。下面的代码向您展示了如何声明和使用它们

private string ddlRoleDs;
private string GvDs;
private string ddMenuDs;

private void Page_Load(object sender, EventArgs e)
{
    // don't declare them here, but you can use them here
    ddlRoleDs = "test value";
    ....
}

在Page_load方法中设置值后,可以在其他方法中使用它们

protected void ddlApp_SelectedIndexChanged(object sender, EventArgs e)
{        
    ddlRole.DataSourceID = ddlRoleDs;
    MenuAssignmentGv.DataSourceID = GvDs;
    ddlMenu.DataSourceID = ddlMenuDs;
}