Avatar of kalittaair
kalittaair asked on

The name 'userFullName' does not exist in the current context

Using VS 2008
C#
.NET 3.5

Getting the error in the title above. See the code below. How can I fix without calling my AD.getfullName method again in the buttonAuthorize_click event? I know my SQL statements are good because if I remove the offending one the other three pieces of data write correctly.

Thanks in advance.
private void main_Load(object sender, EventArgs e)
        {
            //Determine AD user name and full name. These are calls to a custom class I made and these calls work fine.
            string userName = AD.getuserName();
            string userFullName = AD.getfullName(userName);
            
            //Create collection for employee names
            StringCollection employees = new StringCollection();
 
            // userFullName shows up correctly here - so I know my variable is getting populated correctly.
            this.Text = "Crew Reserve Tracker: " + userFullName; 
 
            employees = MISA.getCrew();
                     
             foreach (String employee in employees)
            {
                crewBox.Items.Add(employee);
            }
        }
 
        private void buttonAuthorize_Click(object sender, EventArgs e)
        {
            int randomNumber = RandomNumber(10000, 99000);
            string crewName = crewBox.Text.ToString();
            DateTime now = DateTime.Now;
                       
            //Open connection to SQL DB
            SqlConnection conn =
            new SqlConnection("Data Source=SERVER;Initial Catalog=DB01;Integrated Security=True");
 
            conn.Open();
 
            string sqlInsert = "INSERT INTO Authorizations (Date, AuthNumber, CrewMember, Employee) values (@now, @randomNumber, @crewName, @userFullName)";
 
            SqlCommand sqlCom = new SqlCommand(sqlInsert, conn);
 
            sqlCom.Parameters.AddWithValue("@now", now);
            sqlCom.Parameters.AddWithValue("@randomNumber", randomNumber);
            sqlCom.Parameters.AddWithValue("@crewName", crewName);
            //ERROR OCURS ON THIS LINE 
            sqlCom.Parameters.AddWithValue("@userFullName", userFullName);
 
            sqlCom.ExecuteNonQuery();
            sqlCom.Dispose();
 
            conn.Close();

Open in new window

.NET ProgrammingC#

Avatar of undefined
Last Comment
silemone

8/22/2022 - Mon
silemone

your error appears to be coming from line 41...

see, you're instance of userFullName is not global...it is created INSIDE of the page load method which means userFullName does not exist outside of the page load, but you using it in buttonAuthorize_Click without first declaring it...if you want to do this, then declare it outside of all methods right under class declaration so it can be global.
ASKER
kalittaair

I tried that. Sorry, I should have mentioned that.  When I move the AD calls up like so..
public partial class main : Form
    {
        string userName = AD.getuserName();
        string userFullName = AD.getfullName(userName);
        public main()
        {
            InitializeComponent();
        }

        private void main_Load(object sender, EventArgs e)
        {
          .....
I get "A field initializer cannot reference the non-static field, method, or property" error on the line:
  string userFullName = AD.getfullName(userName); - with userName underlined by VS.

Any other ideas?
ASKER
kalittaair

Is there some way I can somehow pass the userFullName string into the button_click event? I am not having any luck making it global? Anyone?

I have increased the points to 500. I really need to solve  this.

Thanks.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
silemone

more like this:

        string userName = String.Empty;
        string userFullName = String.Empty;
        public main()
        {
            InitializeComponent();
        }

        private void main_Load(object sender, EventArgs e)
        {
           userName = AD.getuserName();
           userFullName = AD.getfullName(userName);
ASKER
kalittaair

OK - I did just that and my errors went away. I make the AD calls in my main_Load and the values are loaded. That is good. However the value of the userName and getFullName variables are empty in my button_click event. I threw in a messagebox in the button_click event to display both values and they are empty.

Any ideas?

angus_young_acdc

Put a breakpoint in userName = AD.getuserName(); and step through to see whats happening.  

Basically it seems that your call for getuserName is not returning anything.  Is it a custom method?  If so your issue will be there.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
silemone

ok...in that case, use session...keep your variables local...here is the code: Session["userName"] = userName in the Page Load....

  string userName = String.Empty;
        string userFullName = String.Empty;
        public main()
        {
            InitializeComponent();
        }

        private void main_Load(object sender, EventArgs e)
        {
           string userName = AD.getuserName();
           string userFullName = AD.getfullName(userName);
           Session("userName") = userName;
           Session("userFullName") = userFullName;
         }
       
         Then when you get to the part/method where they were showing null, reload them from session variable...
   
              string userName = Session("userName").ToString();
              string  userFullName = Session("userFullName").ToString();


        Then use variables as needed.
         

silemone

Corrected:   notice I've made removed global variable     username = String.Empty;


ok...in that case, use session...keep your variables local...here is the code: Session["userName"] = userName in the Page Load....

        //string userName = String.Empty;
        //string userFullName = String.Empty;            make all variables local/derive in method
        public main()
        {
            InitializeComponent();
        }

        private void main_Load(object sender, EventArgs e)
        {
           string userName = AD.getuserName();
           string userFullName = AD.getfullName(userName);
           Session("userName") = userName;
           Session("userFullName") = userFullName;
         }
       
         Then when you get to the part/method where they were showing null, reload them from session variable...
   
              string userName = Session("userName").ToString();
              string  userFullName = Session("userFullName").ToString();


        Then use variables as needed.
         
ASKER
kalittaair

Thank you for your response.

Yes, they are custom methods but they are not the problem. I have code in my main which utilizes the userFullName and that works fine. The code below would not work if my methods were bad.
//Determine AD user name and full name
            string userName = AD.getuserName();
            string userFullName = AD.getfullName(userName);
                       
            //Create collection for employee names
            StringCollection employees = new StringCollection();

            this.Text = "Crew Reserve Tracker: " + userFullName; <---THIS WORKS

userName is used to fetch userFullName. Both methods would need to be successfull for the code above to work, and it does.

I think the problem is that a string is a reference type rather then a value type. So, the instance of it globally is referencing an empty string and the instance of it within the main is referencing the info I need. When I try to use it in my button_click event it is accessing the global reference, an empty string. Could this be the problem? If so, how do I resolve?

Thanks.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
silemone

read my comment  ID:23476246 about using session...  that should fix the problem...


i'll just copy and paste it again

Corrected:   notice I've made removed global variable     username = String.Empty;


ok...in that case, use session...keep your variables local...here is the code: Session["userName"] = userName in the Page Load....

        //string userName = String.Empty;
        //string userFullName = String.Empty;            make all variables local/derive in method
        public main()
        {
            InitializeComponent();
        }

        private void main_Load(object sender, EventArgs e)
        {
           string userName = AD.getuserName();
           string userFullName = AD.getfullName(userName);
           Session("userName") = userName;
           Session("userFullName") = userFullName;
         }
       
         Then when you get to the part/method where they were showing null, reload them from session variable...
   
              string userName = Session("userName").ToString();
              string  userFullName = Session("userFullName").ToString();


        Then use variables as needed.
         
angus_young_acdc

>>> When I try to use it in my button_click event it is accessing the global reference, an empty string. Could this be the problem? If so, how do I resolve?

It shouldnt be.  If you are assigning the string a value when it loads then it shouldn't be null or empty upon a button_click event.  You could check this out by outputing the string in Main after you have assigned its value, in a messagebox/debug/etc.  If its null or empty after:
userFullName = AD.getfullName(userName);

Then nothing is being returned.  In which case I would double check that you are returning the right string info from AD.getfullName.  Seems a long shot, but it could be that before you go "return myString" that you are clearing out its value.  
ASKER
kalittaair

silemone - My previous response was to angus and it appears I was typing it at the same time you were posting, but thank you for re-posting. Now, about your suggestion - I am getting "Session does not exist in the current context". Is there a specific class I need to bring in with a "using" statement? I am bringing in the following:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.DirectoryServices;
using System.Collections.Specialized;
using Kalitta;
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
kalittaair

angus - I do utilize the sring in Main. I change the title bar of the form like so:
this.Text = "Crew Reserve Tracker: " + userFullName;
This works perfectly, so I know my custom AD calls are working fine. The custom method that populates userFullName must accept userName as an argument. Since I can use userFullName to change the title bar I know both AD calls are working. I only experience issues when I try to access the string variables in the button_click event. I appreciate your thoughts on this but the problem does not lie in the custom AD methods.
silemone

I apologize...this is a winform, not a web program...I'll get right back to you.
silemone

Here's one thing you can do...keep them global, but don't initialize them to String.Empty...See it if retains it value then...
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ASKER
kalittaair

silemone - Nope. Same result. Empty in the button_click event. I did the following:

public partial class main : Form
    {
        string userName;
        string userFullName;

        public main()
        {
            InitializeComponent();
        }

        private void main_Load(object sender, EventArgs e)
        {
            //Determine AD user name and full name
            string userName = AD.getuserName();
            string userFullName = AD.getfullName(userName);
....
ASKER CERTIFIED SOLUTION
silemone

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
kalittaair

That's it! Works great. Thank you so much for your persistence in helping me with this!
silemone

I'm just glad we could get it working...good job...

Cheers
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.