[C#] Null Reference Exception未处理 [英] [C#] Null Reference Exception was unhandled

查看:57
本文介绍了[C#] Null Reference Exception未处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不知道为什么它会在表单加载事件中给出。

因为我可以使用这个代码行gridView1.GetDataRow(i)[Shortcut]。ToString()gridView的KeyDown没有任何例外的事件。

I really don't know why it gives at form loading event.
Because I could use this codeline "gridView1.GetDataRow(i)["Shortcut"].ToString()" gridView's KeyDown event without any exceptions.

private void frmShrtct_Load(object sender, EventArgs e)
        {
            this.dt2.Fill(this.ds.SHRT_CUT);
            this.dt.Fill(this.ds.DB_SHORTCUT);
            gridControl1.DataSource = bs;
            SqlCommand forOku = new SqlCommand("SELECT Shortcut FROM DB_SHORTCUT",baglanti);
            baglanti.Open();
           SqlDataReader oku= forOku.ExecuteReader();
           ArrayList names = new ArrayList();
           while (oku.Read())
           {
               names.Add(oku["Shortcut"]);
           }
           forOku.Dispose();
           oku.Dispose();     
           for (int i = 0; i <names.Count ; i++)
           {
              if (names[i] == gridView1.GetDataRow(i)["Shortcut"].ToString()) //this line
                { }
                else
                {
                    gridView1.GetDataRow(i)["Shortcut"] = names[i];
                }
           }
        }

推荐答案

简单:设置DataSource不会立即加载网格与数据 - 它发出信号 DataSourceChanged事件 [ ^ ]到网格,导致它自己加载。由于您位于事件处理程序内,因此事件在当前处理程序完成后排队等待。



在此之前,您无法使用Grid中的数据,因为它还没有加载。



移动你的代码将其用于Form.Shown事件,它应该可以工作。
Simple: setting the DataSource does not immediately load the Grid with data - it signals a DataSourceChanged event[^] to the Grid which causes it to load itself. Since you are inside an event handler, the event is queued for after the current handler finishes.

Until then, you can't use the data in the Grid, because it isn't loaded yet.

Move your code to use it into the Form.Shown event instead, and it should work.


这篇关于[C#] Null Reference Exception未处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆