DataGridView 空引用异常
我有一个 Web 服务,它使用几个 Web 方法填充我的 DataGridView
。
如果没有此代码,一切都会很好,但我需要根据所选的行来更改图片,并且图片的名称将位于不会更改的静态列中。
我想做的是,在我的 webmethod 中,向其发送一个等于 picture1.jpg
的图片名称。
在 Windows 应用程序中,我使用以下代码:
int i;
i = memdataGV.SelectedCells[0].RowIndex;
var pictext = memdataGV.Rows[i].Cells[5].Value.ToString();
pictureBox1.ImageLocation = "C:\\Pictures\\" + pictext;
当 DataGridView 首次填充时,一切正常,但是当我单击其中一个按钮事件时,它会在以下行中引发异常:
var pictext = memdataGV.Rows[i].Cells[5].Value.ToString();
NullReferenceException 未处理
我尝试调试代码,并将 if
语句添加到顶部,但似乎没有修复它。
I have a webservice which populates my DataGridView
using a couple of webmethods.
Without this code everything works great but I need the picture to change depending on the row selected and the name of the picture will be in a static column that will not change.
What I am trying to do is, in my webmethod, send it a picture name equal to picture1.jpg
.
In the windows application I am using this code:
int i;
i = memdataGV.SelectedCells[0].RowIndex;
var pictext = memdataGV.Rows[i].Cells[5].Value.ToString();
pictureBox1.ImageLocation = "C:\\Pictures\\" + pictext;
When the DataGridView
first populates everything works fine but when I click on one of my button events it throws an exception on the following line:
var pictext = memdataGV.Rows[i].Cells[5].Value.ToString();
NullReferenceException was unhandled
I tried to debug the code and I added the if
statement to the top however does not seem to fix it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
三种可能性:
i
的值不正确(例如 -1)Value
为NULL
,因此当您调用ToString()
爆炸了。Cells[5]
不存在。 IE 可能是另一个索引,例如 4。请记住,该索引是从零开始的。根据您的评论,将行更改为:
Three possibilities:
i
has an incorrect value (-1, for example)Value
at Cells[5] isNULL
so when you callToString()
blows up.Cells[5]
does not exist. I.E. maybe it's another index, like 4, for example. The index is zero-based, remember.Based on your comment, change your line to:
发现由于某种原因索引 5 返回 null 并且单元格中有一个值。所以我编写了代码来通过列名获取值,该列名找到了该值并且正在工作
Figured it out for some reason the index 5 was returning null and there was a value in the cell. So I did code to grab the value by the column name which found the value and is working