public partial class Form1 : Form
    {
        public string[] strKey;
        StreamReader reader = new StreamReader("music.db", Encoding.GetEncoding("GB2312"));        public void MyMethod()
        {
            strKey = reader.ReadLine().Split(',');        }        public Form1()
        {
            InitializeComponent();
        }        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listBox1.SelectedItem != null)
            {
                button1.Enabled = true;
            }
        }        public void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.Items != null)
            {
                listBox1.Items.Clear();
            }            while (reader.Peek() > 0)
            {
                string a = comboBox1.SelectedItem.ToString();                if (strKey.Length == 5)
                {
                    if (strKey[2].Trim() == a)
                    {
                        listBox1.Items.Add(strKey[0].Trim() + " - " + strKey[1].Trim());
                     }
                }
            }
            reader.Close();
        }当运行到if (strKey.Length == 5)时,显示未将对象引用设置到对象的实例。。求救。。

解决方案 »

  1.   

    if (strKey!=null&&strKey.Length == 5) 
                    { 
                        if (strKey[2].Trim() == a) 
                        { 
                            listBox1.Items.Add(strKey[0].Trim() + " - " + strKey[1].Trim()); 
                        } 
                    } 
      

  2.   

    你还没给strKey 初始化呢,在if (strKey.Length == 5)前面先调用MyMethod()
      

  3.   

    使用之前貌似没有调用MyMethod()
      

  4.   

    请问Form1 f1 = new Form1();
       f1.MyMethod();
    应放在哪?我放在事件里依然有错,谢谢
      

  5.   

    将strKey初始化放在构造函数里
      

  6.   

            public Form1() 
            { 
                InitializeComponent(); 
                MyMethod();
            } 
      

  7.   

    还是 if (strKey!=null&&strKey.Length == 5) 这句报错么?
      

  8.   

    放在这个事件里的最前面:public void comboBox1_SelectedIndexChanged
    或放在构造函数里。
      

  9.   

      public string[] strKey; 
     这个没有初试化, 你在下面就用了strKey.Length ,很显然是错的
     先对它赋值才行,你在public void MyMethod()  对它赋值了,但是没有调用它,
    你之前定义的strKey是全局变量,所以你在后面用的时候其实是个空值
    建议:用的时候调用MyMethod()方法,或则之前定义的时候就对它赋值。
      

  10.   

    虽然没有报错。。但是当我选择comboBox时程序没反应了
      

  11.   

    没有报错,但是当我选择comboBox时程序没反应了