对象引用不是对象的实例 [英] Object reference not to an instance of an object

查看:81
本文介绍了对象引用不是对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的朋友们,



我创建了一个Gridview复选框列..它有以下错误请帮帮我..

对象引用不要if语句中的对象实例:





Dear Frnds,

I have created one Gridview checkbox column.. it have following error pls help me..
Object reference not to an instance of an object in if Statement:


foreach (DataGridViewRow row in dgvScreenDetails.Rows)
           {
               DataGridViewCheckBoxCell chk = row.Cells[2] as DataGridViewCheckBoxCell;
               // number 0 represents the 1st column of dgv!

               if (Convert.ToBoolean(chk.Value) == true)
               {
                   MessageBox.Show("this cell checked");

               }
           }

推荐答案

使用调试器并检查,但我想你会发现那行.Cells [2]不是DataGridViewCheckBoxCell - 所以返回一个null,你得到一个错误。



从调试器开始,看看实际上是什么类型:应该告诉你的是你正在读错列,或者它是一个空单元格,或者是什么 - 我们不能这样做,因为我们看不到你的屏幕,我们没有你的硬盘驱动器,我们无法读懂你的想法! :笑:
Use the debugger and check, but I think you will find that row.Cells[2] is not a DataGridViewCheckBoxCell - so as returns a null, and you get an error.

Start with the debugger, and look at what type is actually is: that should tell you is you are reading the wrong column, or it's an empty cell, or what - we can't do that because we can't see your screen, we don't have access to you HDD, and we can't read your mind! :laugh:


粘贴代码块将检查


DataGridViewCheckBoxCell chk = row.Cells[2] as DataGridViewCheckBoxCell;



如果类型转换失败,关键字将返回null。在 if 语句中使用变量之前,需要检查变量是否为null。 chk 变量为空。


The as keyword will return null if the type conversion failed. You need to check if the variable is null before using it in the if statement. The chk variable is null.


这篇关于对象引用不是对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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