C#异常处理 [英] C# Exception handling
问题描述
我想知道是否有一种更雄辩的方式来表达下面的代码?我似乎无法使用IsNullOrEmpty方法来处理DataGridView中的数据,因此,每当单元格为null时,都会引发异常.
这可行,但似乎有点解决(也许没有解决),并且在检查网格中复选框的值时遇到了相同的问题,这导致我为此编写了更多代码.
任何建议都将不胜感激.
I am wondering if there is a more eloquent way to express the code below? I can''t seem to get the IsNullOrEmpty method to work with data inside of a DataGridView so whenever a cell is null an exception is thrown.
This works, but it seems to be a bit of a work around (maybe not) and I have the same issue when checking the value of a checkbox in the grid which caused me to write more code for that work around.
Any suggestions are greatly appreciated.
private bool IsRowValid( DataGridViewRow row )
{
bool retVal = false;
try
{
if( ( string.IsNullOrEmpty( row.Cells[ "Quantity" ].Value.ToString() ) != true ) &&
( string.IsNullOrEmpty( row.Cells[ "Unit" ].Value.ToString() ) != true ) &&
( string.IsNullOrEmpty( row.Cells[ "Cell" ].Value.ToString() ) != true ) &&
( string.IsNullOrEmpty( row.Cells[ "Station" ].Value.ToString() ) != true ) )
{
retVal = true;
}
}
catch( NullReferenceException )
{
retVal = false;
}
return retVal;
}
推荐答案
该代码中的问题是row.Cells[ "Quantity" ].Value
可以是null
,但是您在不检查该对象的情况下调用了ToString
.
变更:
The problem in that code is thatrow.Cells[ "Quantity" ].Value
can benull
, but you callToString
on that without checking for that.
Change:
string.IsNullOrEmpty( row.Cells[ "Quantity" ].Value.ToString() )
到
to
string.IsNullOrEmpty( row.Cells[ "Quantity" ].Value as String)
顺便说一句,请不要执行!= true
,这很难看,也不建议您这样做.而是这样做:
Btw please don''t do != true
, that''s ugly to see and not recommended practice. Instead do this:
if( !String.IsNullOrEmpty(...))...
我不知道有什么更优雅的方法,尽管有人可能会知道.
我唯一要说的是,它可能会略短一些
I don''t know of a more elegant way, although somebody probably will.
The only thing I would say is that it could be very slightly shorter
if ( ( !string.IsNullOrEmpty( row.Cells[ "Quantity"].Value.ToString() )) &&
( !string.IsNullOrEmpty( row.Cells[ "Unit"].Value.ToString() )) &&
( !string.IsNullOrEmpty( row.Cells[ "Cell"].Value.ToString() )) &&
( !string.IsNullOrEmpty( row.Cells[ "Station"].Value.ToString() )) )
可能会牺牲可读性.
possibly at the expense of readability.
这篇关于C#异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!