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)时,显示未将对象引用设置到对象的实例。。求救。。
{
if (strKey[2].Trim() == a)
{
listBox1.Items.Add(strKey[0].Trim() + " - " + strKey[1].Trim());
}
}
f1.MyMethod();
应放在哪?我放在事件里依然有错,谢谢
{
InitializeComponent();
MyMethod();
}
或放在构造函数里。
这个没有初试化, 你在下面就用了strKey.Length ,很显然是错的
先对它赋值才行,你在public void MyMethod() 对它赋值了,但是没有调用它,
你之前定义的strKey是全局变量,所以你在后面用的时候其实是个空值
建议:用的时候调用MyMethod()方法,或则之前定义的时候就对它赋值。