dgv内容为空时报错,System.Windows.Forms.DataGridViewCell.Value.get 返回 null。

唄小白 2021-04-26 05:33:42
System.NullReferenceException:“未将对象引用设置到对象的实例。”System.Windows.Forms.DataGridViewCell.Value.get 返回 null。 求大神指导下,要怎么处理: string beizhu; if (Convert.ToString(dataGridView1.Rows[i].Cells["bz"].Value.ToString()) != "") { beizhu = dataGridView1.Rows[i].Cells["bz"].Value.ToString(); } else { beizhu = "NULL"; }
...全文
1551 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
叶落花开 2021-10-16
  • 打赏
  • 举报
回复

用Convert.ToString转换

wang_peng 2021-04-27
  • 打赏
  • 举报
回复
最好从数据源处理, 在数据源里的所有列都给默认值, 要不然你用一个值,就得判读一次, 这得多多少代码量
morliz子轩 2021-04-27
  • 打赏
  • 举报
回复
如果bz字段,不存在null,只存在为空的情况。 还可以写成: string beizhu = dataGridView1.Rows[i].Cells["bz"].Value.ToString()??"";
morliz子轩 2021-04-27
  • 打赏
  • 举报
回复 1

//对null值的处理,不需要这么费劲

string beizhu = dataGridView1.Rows[i].Cells["bz"].Value !=null ? dataGridView1.Rows[i].Cells["bz"].Value.ToString() : "";

哎嘿嘿嘿 2021-04-27
  • 打赏
  • 举报
回复 1
beizhu= dataGridView1.Rows[1].Cells["bz"].Value?.ToString();
爱喝茶的助手 2021-04-27
  • 打赏
  • 举报
回复 1
string beizhu;
                if (dataGridView1.Rows[i].Cells["bz"].Value==null  || dataGridView1.Rows[i].Cells["bz"].Value.ToString()== "")
                {
                   beizhu = "NULL";
                }
                else
                {
                     beizhu = dataGridView1.Rows[i].Cells["bz"].Value.ToString();
                }
蜗牛慢慢趴 2021-04-26
  • 打赏
  • 举报
回复

string beizhu;
                if (dataGridView1.Rows[i].Cells["bz"].Value!=null  && dataGridView1.Rows[i].Cells["bz"].Value.ToString() != "")
                {
                    beizhu = dataGridView1.Rows[i].Cells["bz"].Value.ToString();
                }
                else
                {
                    beizhu = "NULL";
                }

110,502

社区成员

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

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

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