Link to home
Start Free TrialLog in
Avatar of stephenlecomptejr
stephenlecomptejrFlag for United States of America

asked on

How to overcome error - An object reference is required for the non-static field, method or property for a combo box?

I get an error that states - An object reference is required for the non-static field, method or property and its for a combo box but I don't know how to rewrite the syntax to allow for rebuild.

I'm guessing I need to make a change in the frmMain.Designer.cs file and place a static value for cbFrom - but not sure where it exactly should be and what the syntax should be...

The first part of the code is where the error is occuring with the highlight on line: sFrom = cbFrom.SelectedIndex;   with the underline on cbFrom

Please note I am learning C# for the first time so please forgive me.  =)
//module where error for rebuild appears -

private static void Rename_Extension_Files_In_Folder(string sFile)
        {
            string sFileAdjusted;
            string sFrom;
            string sTo;
            //line item where code is appearing -
            sFrom = cbFrom.SelectedIndex;
            sTo = cbTo.SelectedIndex;
            sFileAdjusted = Regex.Replace(sFile, sFrom, sTo);

            File.Copy(sFile, sFileAdjusted);
            if (File.Exists(sFileAdjusted) == true)
            {
                File.Delete(sFile);
            }
            else
            {

            }
        }


//frmMain.Designers form code starts here
//
//
namespace FileExtRenamer
{
    partial class frmMain
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
            this.cbFrom = new System.Windows.Forms.ComboBox();
            this.cbTo = new System.Windows.Forms.ComboBox();
            this.txtPath = new System.Windows.Forms.TextBox();
            this.btnBrowse = new System.Windows.Forms.Button();
            this.btnRename = new System.Windows.Forms.Button();
            this.lblFrom = new System.Windows.Forms.Label();
            this.lblTo = new System.Windows.Forms.Label();
            this.chkSubFolders = new System.Windows.Forms.CheckBox();
            this.btnCancel = new System.Windows.Forms.Button();
            this.fBDialog = new System.Windows.Forms.FolderBrowserDialog();
            this.txtDeep = new System.Windows.Forms.TextBox();
            this.lblDeep = new System.Windows.Forms.Label();
            this.lblRenameOpts = new System.Windows.Forms.Label();
            this.lblSearchOpts = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // cbFrom
            // 
            this.cbFrom.BackColor = System.Drawing.SystemColors.Control;
            this.cbFrom.CausesValidation = false;
            this.cbFrom.FormattingEnabled = true;
            this.cbFrom.Items.AddRange(new object[] {
            ".txt",
            ".csv",
            ".xls",
            ".xlsx"});
            this.cbFrom.Location = new System.Drawing.Point(14, 48);
            this.cbFrom.Name = "cbFrom";
            this.cbFrom.Size = new System.Drawing.Size(99, 21);
            this.cbFrom.TabIndex = 4;
            // 
            // cbTo
            // 
            this.cbTo.BackColor = System.Drawing.SystemColors.Control;
            this.cbTo.FormattingEnabled = true;
            this.cbTo.Items.AddRange(new object[] {
            ".txt",
            ".csv",
            ".xls",
            ".xlsx"});
            this.cbTo.Location = new System.Drawing.Point(119, 48);
            this.cbTo.Name = "cbTo";
            this.cbTo.Size = new System.Drawing.Size(106, 21);
            this.cbTo.TabIndex = 5;
            // 
            // txtPath
            // 
            this.txtPath.BackColor = System.Drawing.SystemColors.Control;
            this.txtPath.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.txtPath.Location = new System.Drawing.Point(14, 110);
            this.txtPath.Multiline = true;
            this.txtPath.Name = "txtPath";
            this.txtPath.Size = new System.Drawing.Size(211, 56);
            this.txtPath.TabIndex = 7;
            // 
            // btnBrowse
            // 
            this.btnBrowse.Location = new System.Drawing.Point(158, 172);
            this.btnBrowse.Name = "btnBrowse";
            this.btnBrowse.Size = new System.Drawing.Size(67, 24);
            this.btnBrowse.TabIndex = 8;
            this.btnBrowse.Text = "Browse";
            this.btnBrowse.UseVisualStyleBackColor = true;
            this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
            // 
            // btnRename
            // 
            this.btnRename.Location = new System.Drawing.Point(85, 290);
            this.btnRename.Name = "btnRename";
            this.btnRename.Size = new System.Drawing.Size(67, 24);
            this.btnRename.TabIndex = 13;
            this.btnRename.Text = "Rename";
            this.btnRename.UseVisualStyleBackColor = true;
            this.btnRename.Click += new System.EventHandler(this.btnRename_Click);
            // 
            // lblFrom
            // 
            this.lblFrom.AutoSize = true;
            this.lblFrom.Location = new System.Drawing.Point(11, 32);
            this.lblFrom.Name = "lblFrom";
            this.lblFrom.Size = new System.Drawing.Size(33, 13);
            this.lblFrom.TabIndex = 2;
            this.lblFrom.Text = "From:";
            // 
            // lblTo
            // 
            this.lblTo.AutoSize = true;
            this.lblTo.Location = new System.Drawing.Point(116, 32);
            this.lblTo.Name = "lblTo";
            this.lblTo.Size = new System.Drawing.Size(23, 13);
            this.lblTo.TabIndex = 3;
            this.lblTo.Text = "To:";
            // 
            // chkSubFolders
            // 
            this.chkSubFolders.AutoSize = true;
            this.chkSubFolders.Checked = true;
            this.chkSubFolders.CheckState = System.Windows.Forms.CheckState.Checked;
            this.chkSubFolders.Location = new System.Drawing.Point(14, 215);
            this.chkSubFolders.Name = "chkSubFolders";
            this.chkSubFolders.Size = new System.Drawing.Size(115, 17);
            this.chkSubFolders.TabIndex = 10;
            this.chkSubFolders.Text = " Include subfolders";
            this.chkSubFolders.UseVisualStyleBackColor = true;
            // 
            // btnCancel
            // 
            this.btnCancel.Location = new System.Drawing.Point(158, 290);
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Size = new System.Drawing.Size(67, 24);
            this.btnCancel.TabIndex = 0;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
            // 
            // txtDeep
            // 
            this.txtDeep.Enabled = false;
            this.txtDeep.Location = new System.Drawing.Point(10, 238);
            this.txtDeep.Name = "txtDeep";
            this.txtDeep.Size = new System.Drawing.Size(19, 20);
            this.txtDeep.TabIndex = 11;
            this.txtDeep.Text = "4";
            // 
            // lblDeep
            // 
            this.lblDeep.AutoSize = true;
            this.lblDeep.Location = new System.Drawing.Point(32, 241);
            this.lblDeep.Name = "lblDeep";
            this.lblDeep.Size = new System.Drawing.Size(154, 13);
            this.lblDeep.TabIndex = 12;
            this.lblDeep.Text = "# limit of folders deep to search";
            // 
            // lblRenameOpts
            // 
            this.lblRenameOpts.AutoSize = true;
            this.lblRenameOpts.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblRenameOpts.Location = new System.Drawing.Point(11, 9);
            this.lblRenameOpts.Name = "lblRenameOpts";
            this.lblRenameOpts.Size = new System.Drawing.Size(100, 13);
            this.lblRenameOpts.TabIndex = 1;
            this.lblRenameOpts.Text = "Rename Options";
            // 
            // lblSearchOpts
            // 
            this.lblSearchOpts.AutoSize = true;
            this.lblSearchOpts.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblSearchOpts.Location = new System.Drawing.Point(11, 183);
            this.lblSearchOpts.Name = "lblSearchOpts";
            this.lblSearchOpts.Size = new System.Drawing.Size(94, 13);
            this.lblSearchOpts.TabIndex = 9;
            this.lblSearchOpts.Text = "Search Options";
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(11, 94);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(74, 13);
            this.label1.TabIndex = 6;
            this.label1.Text = "From folder:";
            // 
            // frmMain
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.White;
            this.ClientSize = new System.Drawing.Size(240, 336);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.lblSearchOpts);
            this.Controls.Add(this.lblRenameOpts);
            this.Controls.Add(this.lblDeep);
            this.Controls.Add(this.txtDeep);
            this.Controls.Add(this.btnCancel);
            this.Controls.Add(this.chkSubFolders);
            this.Controls.Add(this.lblTo);
            this.Controls.Add(this.lblFrom);
            this.Controls.Add(this.btnRename);
            this.Controls.Add(this.btnBrowse);
            this.Controls.Add(this.txtPath);
            this.Controls.Add(this.cbTo);
            this.Controls.Add(this.cbFrom);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.Name = "frmMain";
            this.Text = "1";
            this.Load += new System.EventHandler(this.frmMain_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ComboBox cbFrom;
        private System.Windows.Forms.ComboBox cbTo;
        private System.Windows.Forms.TextBox txtPath;
        private System.Windows.Forms.Button btnBrowse;
        private System.Windows.Forms.Button btnRename;
        private System.Windows.Forms.Label lblFrom;
        private System.Windows.Forms.Label lblTo;
        private System.Windows.Forms.CheckBox chkSubFolders;
        private System.Windows.Forms.Button btnCancel;
        private System.Windows.Forms.FolderBrowserDialog fBDialog;
        private System.Windows.Forms.TextBox txtDeep;
        private System.Windows.Forms.Label lblDeep;
        private System.Windows.Forms.Label lblRenameOpts;
        private System.Windows.Forms.Label lblSearchOpts;
        private System.Windows.Forms.Label label1;
        
    }
}

Open in new window

Avatar of bklmnsh
bklmnsh
Flag of Ukraine image

private static void Rename_Extension_Files_In_Folder(string sFile)

remove the static keyword from method declaration
- If you defined the Rename_Extension_Files_In_Folder in your winform class, there is no need to have it as static
- If you need this method to be static you should pass ComboBox variables as the parameters, ie:

private static void Rename_Extension_Files_In_Folder(string sFile, DropDownList cbFrom, DropDownList cbTo)
Avatar of Ravi Vaddadi
Where is your Rename_Extension_Files_In_Folder method defined?

Remove the static  in the method signature. Make it

private void Rename_Extension_Files_In_Folder(string sFile)

private void Rename_Extension_Files_In_Folder(string sFile)
        {
            string sFileAdjusted;
            string sFrom;
            string sTo;
            //line item where code is appearing -
            sFrom = cbFrom.SelectedIndex.ToString();
            sTo = cbTo.SelectedIndex.ToString();
            sFileAdjusted = Regex.Replace(sFile, sFrom, sTo);

            File.Copy(sFile, sFileAdjusted);
            if (File.Exists(sFileAdjusted) == true)
            {
                File.Delete(sFile);
            }
            else
            {

            }
        }
ASKER CERTIFIED SOLUTION
Avatar of lazyberezovsky
lazyberezovsky
Flag of Belarus image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

private void Rename_Extension_Files_In_Folder(string sFile)
        {
            
            string sFrom = cbFrom.SelectedItem.ToString();
            string sTo = cbTo.SelectedItem.ToString();          
            string sFileAdjusted = Regex.Replace(sFile, sFrom, sTo);

            File.Copy(sFile, sFileAdjusted);
            if (File.Exists(sFileAdjusted) == true)
            {
                File.Delete(sFile);
            }            
        }

Open in new window

Avatar of stephenlecomptejr

ASKER

bklmnsh, when I try your code obviously I get the second error as lazyberezovsky stated

SriVaddadi and lazyberezovsky, when I copy and paste your code - I get another error -

An object reference is required for the non-static field, method, or property 'FileExtRenamer.frmMain.Rename_Extension_Files_In_Folder(string)

with the highlight on Rename_Extension_Files_In_Folder(fileName); in another static void.

Allow me to post the full code that is under frmMain.cs and please don't roll the eyes too much at it.  I'm still learning and any explanataions are appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;


namespace FileExtRenamer
{
    public partial class frmMain : Form
    {
        

        public frmMain()
        {
            InitializeComponent();
        }


        private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            string sPath;
            sPath = txtPath.Text;
            fBDialog.SelectedPath = sPath;
            fBDialog.ShowDialog();
            txtPath.Text = fBDialog.SelectedPath;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            txtPath.Text = @"G:\pj\";
            cbFrom.Text = ".txt";
            cbTo.Text = ".csv";
            btnBrowse.Focus();
        }

        private void btnRename_Click(object sender, EventArgs e)
        {
            string sPath;
            sPath = txtPath.Text;

            switch (sPath)
            {
                case "":
            
                MessageBox.Show("You have not selected a folder.  Please click 'Browse' to continue.");
                break;

                //case (@I:\proj"):
                //MessageBox.Show("Folder too large to search.");

            }

            DialogResult dlgResult = MessageBox.Show("Are you sure you want to rename all files in this folder?", "Continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlgResult == DialogResult.Yes)
            {
                // Yes, continue 
                Rename_Folder(sPath);
            }
            else if (dlgResult == DialogResult.No)
            {
                // No, stop
            }

        }

        private void Rename_Folder(string sFullPath)
        {
            //
            if (chkSubFolders.Checked == true)
            {
                string text = txtDeep.Text;
                int num = int.Parse(text);
                ProcessDir_wSub(sFullPath, num);
            }
            else
            {
                ProcessDir(sFullPath);
            }


        }

        const int HowDeepToScan = 4;

        public static void ProcessDir_wSub(string sourceDir, int recursionLvl)
        {
            if (recursionLvl <= HowDeepToScan)
            {
            // Process the list of files found in the directory. 
            string[] fileEntries = Directory.GetFiles(sourceDir);
            foreach (string fileName in fileEntries)
            {
                // do something with fileName

                Rename_Extension_Files_In_Folder(fileName);
                Console.WriteLine(fileName);

            }


            // Recurse into subdirectories of this directory.
            string[] subdirEntries = Directory.GetDirectories(sourceDir);
            foreach (string subdir in subdirEntries)
             //Do not iterate through reparse points
            if ((File.GetAttributes(subdir) &
               FileAttributes.ReparsePoint) !=
                   FileAttributes.ReparsePoint)

                ProcessDir_wSub(subdir, recursionLvl + 1);
            }
        }

        public static void ProcessDir(string sourceDir)
        {
            //if (recursionLvl <= HowDeepToScan)
            //{
            // Process the list of files found in the directory. 
            string[] fileEntries = Directory.GetFiles(sourceDir);
            foreach (string fileName in fileEntries)
            {
                // do something with fileName
                Rename_Extension_Files_In_Folder(fileName);
                Console.WriteLine(fileName);
            }


            // Recurse into subdirectories of this directory.
            //string[] subdirEntries = Directory.GetDirectories(sourceDir);
            //foreach (string subdir in subdirEntries)
            // Do not iterate through reparse points
            //if ((File.GetAttributes(subdir) &
            //   FileAttributes.ReparsePoint) !=
            //       FileAttributes.ReparsePoint)

            //  ProcessDir(subdir, recursionLvl + 1);
            //}
        }

        private void Rename_Extension_Files_In_Folder(string sFile)
        {
            string sFileAdjusted;
            string sFrom;
            string sTo;
            //line item where code is appearing -
            sFrom = cbFrom.SelectedIndex.ToString();
            sTo = cbTo.SelectedIndex.ToString();
            sFileAdjusted = Regex.Replace(sFile, sFrom, sTo);

            File.Copy(sFile, sFileAdjusted);
            if (File.Exists(sFileAdjusted) == true)
            {
                File.Delete(sFile);
            }
            else
            {

            }
        }
        
    }
}

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
There is simple rule - you cannot use non-static members in static methods.
Why? Because static members and methods do not belong to any of class instances - they are type members. If you have five objects of class X, which one's field should be used in static method? No one can tell, so and C# compiler can not tell this :)
SriVaddadi,

regarding:
private void Rename_Extension_Files_In_Folder(string sFile)
        {
            string sFileAdjusted;
            string sFrom;
            string sTo;
            //line item where code is appearing -
            sFrom = cbFrom.SelectedIndex.ToString();
            sTo = cbTo.SelectedIndex.ToString();
            sFileAdjusted = Regex.Replace(sFile, sFrom, sTo);

            File.Copy(sFile, sFileAdjusted);
            if (File.Exists(sFileAdjusted) == true)
            {
                File.Delete(sFile);
            }
            else
            {

            }
        }
For the values on sFrom and sTo that are equal to what the combo boxes should be
sFrom is showing a value of  "0" and sTo is showing a value of "1"
whereas the values selected for sFrom = ".txt" and the second value for sTo = ".csv"

oh okay...just apply lazyberezovsky:'s SelectedItem instead of SriVaddadi's SelectedIndex.

I'm splitting the points between both - if okay?
The question was following: "How to overcome error - An object reference is required for the non-static field, method or property for a combo box"
I provided a complete answer how to overcome the given error and moreover commented it first. I don't believe the points are assigned correctly.
I respectfully disagree.

Merely removing the static keyword from method declaration did not solve my problem.
I need code edited to where I can copy and paste that would work in my situation.

It's not a complete answer if it doesn't allow me to run my code successfully.
And I didn't see a reply as much as from the others after I stated I still have issues.

Even if I were to split - you would still get the lowest number of points that I would out of 3 people.
Being new to C# and the simple fact that if I could phrase my question in the right way in the first place then I probably could solve my own problem.  It's not about just merely answering the question.  It's about solving the entire problem of which I wouldn't have come here in the first place where I could go to other forums.  I read the same answer you provided on other websites and removing one word didn't help before.

Telling me to remove the static keyword will help me go look in a book for the answer but I pay money to get the solution to my problem so I don't have to conduct a learning class.

I use this site because I'm learning 20+ other things at the same time.  I've been working 100+ hours a week and coming up with other solutions for MIcrosoft Access, Visual Basic. NET programs and SQL Server all at the same time with deadlines (maybe just like you).  And this is the first time I've got a breather to really respond and look more closely.

I understand the rules about first answer provided gets all the points - but the answer is about communication and the others communicated it more clearly whereas I still don't understand your answer until I go look up online what you state and learn further my C# development.

Even with all thisi I'm still willing to split it evenly 500 between three people - if both lazyberezovsky and SriVaddadi: are open to it and reply back.

Thank you all for all your comments and I hope you do so again in the future!
Hi stephenlecomptejr,

Thank you for detailed comment regarding the motivation of your decision. I can agree or disagree with you in some statements, however there is no need to reassign the points.
I wish you luck in learning C# and hope I will have a chance to help you with any further questions.

Thanks,
Andrew