开发者

Variable scoping on asp.net codebehind in c# (hopefully a no brainer!)

开发者 https://www.devze.com 2023-02-17 07:56 出处:网络
I have an asp.net page (C# codebehind), and in page_load there are various linq queries returning anonymous types, such as:

I have an asp.net page (C# codebehind), and in page_load there are various linq queries returning anonymous types, such as:

var customersAdded = from r in AddedRecords
                                 select new { Ref = r.CustomerRef, Name = r.Customer_Name };

On the page I have a button called 'export to excel', and in that buttonClick event I try to refer to customersAdded. It says it doesn't exist in the context. I know I've overcome similar issues in the past using things along the lines of:

if (File.Exists(System.Web.HttpContext.Current.Server.MapP开发者_如何学运维ath("~/App_Variants/" + GetUserTheme().ToString() + "/images/" + i.ImageUrl)))

But haven't had luck so far.

So question is, how to refer to the variable? And for reference, if I say wanted to refer to a value in a control (eg a textbox on the page) would the same or different approach apply?

Thanks!

Mark


It looks like you just declared your variable as a local variable to Page_Load. To refer to the variable in any other method, it would at least need to be a member of the class. Of course, you're using an anonymous type, and the type itself also needs to be in scope.

One way to address the issue would be to declare the type within the class, probably just as an inner struct. Then, the type is no longer anonymous, so you're free to declare a class member as a collection of your new type. You can assign to that variable in Page_Load, then access the variable elsewhere in your class.

Edit:

The variety of "lazy-loading" I am referring to in my comment is not the language feature with the lazy keyword, nor anything involving yield, etc., but rather just this:

private IQueryable<AddedRecord> _customersAdded;

// make this public if you want to access outside the class
private IQueryable<AddedRecord> CustomersAdded
{
    get
    {
        if (_customersAdded == null)
        {
            // replace next statement with the query you need
            _customersAdded = AddedRecords.Where(something);
        }
        return _customersAdded;
    }
}

Now, if you need more parameters to make this query happen, you can always populate _customersAdded ahead of time. This is kind of a trivial example, admittedly.

0

精彩评论

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

关注公众号