Jump to content

Super easy Noob question

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
williamevanl

williamevanl

    Learning Programmer

  • Members
  • PipPipPip
  • 61 posts
Why are this functions variables outside of the scope of the code above it??

private void fclsMain_Load(object sender, EventArgs e)
        {
            InitializeComponent();
            m_cnADONetConnection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SimpleTest.MDB;Mode=ReadWrite;Persist Security Info=False";
            OleDbCommandBuilder m_cbCommandBuilder = new OleDbCommandBuilder(m_daDataAdapter);
            m_daDataAdapter = new OleDbDataAdapter("Select * From Contacts", m_cnADONetConnection);
            DataTable m_dtContacts = new DataTable();
            m_daDataAdapter.Fill(m_dtContacts);

            int m_rowPosition = 0;

            DataRow m_rwContact = m_dtContacts.Rows[0];
            m_rwContact["Animal"] = "Dinosaur";
            this.ShowCurrentRecord();
        }

        private void ShowCurrentRecord()
        {
            if (m_dtContacts.Rows.Count == 0)
            {
                txtContactName.Text = "";
                txtState.Text = "";
                return;
            }
            txtContactName.Text =
             m_dtContacts.Rows[m_rowPosition]["ContactName"].ToString();
            txtState.Text = m_dtContacts.Rows[m_rowPosition]["State"].ToString();
        }

In other words the compiler error is m_dContacts doesn't exist in current context. What am I missing? I've tried changing private to public etc...

#2
semprance

semprance

    Programmer

  • Members
  • PipPipPipPip
  • 126 posts
It's in the body of a different method.

One solution is to declare the DataTable 'm_dtContacts' within the body of the class, so that all the methods of that class can use it.

EDIT: Didn't realise the top method was calling the bottom method - Instead, change the declaration of ShowCurrentRecord() to ShowCurrentRecord(DataTable d), and change the call to it in fclsMain to pass it as a parameter.

Edited by semprance, 15 April 2010 - 10:03 AM.
Tired.


#3
williamevanl

williamevanl

    Learning Programmer

  • Members
  • PipPipPip
  • 61 posts
Thanks, that worked. I don't understand though shouldn't there be a way to make the variables declared in one method available in another?

#4
semprance

semprance

    Programmer

  • Members
  • PipPipPipPip
  • 126 posts
Hehe, I like the way you said that with such conviction but the only way to provide any non-static and non-class-member variables is to pass them as a parameter. That's what parameters are for.

It's also worth noting what is legal and what is not in terms of code blocks surrounded by {}


{
    int a;
    {
        int b;
        a = 10; //Legal
    }

    b = 5; //Compile error
}


They have a broader explanation here.