datasource报错object reference not set to an instance of an object for combo box

guaili1752 2017-05-16 11:29:43
private void Form_Load(object sender, EventArgs e)
{
string[] installs = new string[] { "Dailymovement", "FDPS" };
comboBox2.Items.AddRange(installs);
comboBox2.SelectedIndex = 0;
}

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
int s = 0;
foreach (Control c in this.Controls)
{

if (c is ListBox)
{
s++;
}

}
for (int ss=1;ss<=s;ss++)
{
ListBox tb = this.Controls["listBox" + ss] as ListBox;

if (comboBox2.SelectedItem.ToString() == "Dailymovement")
{
MySqlCommand cmd1 = new MySqlCommand("select field_name from Dailymovement_name ", con);
MySqlDataAdapter adp1 = new MySqlDataAdapter();
adp1.SelectCommand = cmd1;
DataSet ds1 = new DataSet();
adp1.Fill(ds1, "field");
tb.DataSource = ds1.Tables["field"];
tb.DisplayMember = "field_name";
tb.ValueMember = "field_name";
}
}
}
form load时comboBox2_SelectedIndexChanged事件里 tb.DataSource = ds1.Tables["field"];这句报错,object reference not set to an instance of an object for combo box.为什么有这个错,怎么改
...全文
154 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
正怒月神 2017-05-16
  • 打赏
  • 举报
回复
2个问题,首先 确认tb.DataSource = ds1.Tables["field"]; ds1中是否存在fieId这张表。或者你直接可以调试查看 ds.Tables.Count看看数目 然后给comboBox2items.AddRange()你应该看看这个方法的参数
guaili1752 2017-05-16
  • 打赏
  • 举报
回复
引用 5 楼 hanjun0612 的回复:
[quote=引用 4 楼 guaili1752 的回复:] 应该是 comboBox2.SelectedIndex = 0;触发SelectedIndexChanged事件导致的错误吧
是啊,那不还是回到了之前的问题吗。[/quote] 表确实没问题啊,所有数据都能重新加载出来,所以不知道catch里报的错是怎么回事
正怒月神 2017-05-16
  • 打赏
  • 举报
回复
引用 4 楼 guaili1752 的回复:
应该是 comboBox2.SelectedIndex = 0;触发SelectedIndexChanged事件导致的错误吧
是啊,那不还是回到了之前的问题吗。
guaili1752 2017-05-16
  • 打赏
  • 举报
回复
引用 3 楼 hanjun0612 的回复:
我这里单独执行 下面的语句,没有问题啊
string[] installs = new string[] { "Dailymovement", "FDPS" };
                comboBox2.Items.AddRange(installs);
                comboBox2.SelectedIndex = 0;
而且就报错的内容来说,好像也不是下标的问题
应该是 comboBox2.SelectedIndex = 0;触发SelectedIndexChanged事件导致的错误吧
正怒月神 2017-05-16
  • 打赏
  • 举报
回复
我这里单独执行 下面的语句,没有问题啊
string[] installs = new string[] { "Dailymovement", "FDPS" };
                comboBox2.Items.AddRange(installs);
                comboBox2.SelectedIndex = 0;
而且就报错的内容来说,好像也不是下标的问题
guaili1752 2017-05-16
  • 打赏
  • 举报
回复
引用 1 楼 hanjun0612 的回复:
2个问题,首先 确认tb.DataSource = ds1.Tables["field"]; ds1中是否存在fieId这张表。或者你直接可以调试查看 ds.Tables.Count看看数目 然后给comboBox2items.AddRange()你应该看看这个方法的参数
如果我把load里的 comboBox2.SelectedIndex = 0;注释掉就不会报错啊,SelectedIndexChanged事件本身没有问题,是初始化产生的问题,但是不明白这是什么问题

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧