none
An object reference is required for the nonstatic field, method, or property

    Question

  • I have this error "An object reference is required for the nonstatic field, method, or property" at this line:

            private static void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
            {
                UpdateProgress.Maximum = e.TotalBytesToReceive;
            }


    But if i make the void Non-Static, i have the same error here:

                client.DownloadProgressChanged += Client_DownloadProgressChanged;

    Full Code:

            public static void Updateing()
            {
                WebClient client = new WebClient();
                client.DownloadProgressChanged += Client_DownloadProgressChanged;
                client.DownloadFileCompleted += Client_DownloadFileCompleted;
                client.DownloadFile(new Uri("Url"), "Location");
            }
    
            private static void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
            {
                MessageBox.Show("Download Complete");
            }
    
            private static void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
            {
                UpdateProgress.Maximum = e.TotalBytesToReceive;
            }



    Monday, April 24, 2017 6:51 PM

Answers

  • The last two method needs to be non-static, just change the signatures of them to be:

    private void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
        MessageBox.Show("Download Complete");
    }
    
    private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        UpdateProgress.Maximum = e.TotalBytesToReceive;
    }

    Actually instance variables cannot be accessed inside static method, and you don't actually need these event handlers to be static, i don't understand why you made them static.

    And your other method could be static or non-static, but it is not clear from your shown code why the first method is made static, but this should at least will make your code build and run:

    Hope it helps!



    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites



    Monday, April 24, 2017 8:18 PM