我有listBox1,但是当我在“单击”按钮内部使用该listBox1时,但在“单击”按钮外部使用时,我无法访问。
我在哪里犯错?谢谢

namespace design
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add(button1.Text);// I can access listBox1 here...
        }

        listBox1.//I can't access listBox1 here....
    }
}

最佳答案

您的代码是错误的。您需要将listBox1放入某种方法中以进行访问。

namespace design
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add(button1.Text); // This part is inside a event click of a button. This is why you can access this.
        }

        public void accessList()
        {
            listBox1.Items.Add(button1.Text); // You'll be able to access it here. Because you are inside a method.
        }
        // listBox1. // you'll NEVER access something like this. in this place
    }
}


Maybe you wanna do a property ?

关于c# - 无法访问listBox1,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11542451/

10-09 05:37