且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中使用trim for datagrid?

更新时间:2023-12-03 20:09:46

你只能修剪一个字符串变量,你得到的错误是值是一个对象。你如何处理这个问题取决于细胞中的内容。解决方案可能是

You can only "Trim" on a string variable, the error you are getting suggested that "Value" is an object. How you deal with this depends on what is in the cell. The solution might be
SourcePageFile = SourceFolder + "\\pg-" + Convert.ToDecimal(DataGridView1.Rows[irow].Cells[0].Value.ToString().Trim(' ')) - 1 + ".jpg"






or

SourcePageFile = SourceFolder + "\\pg-" + Convert.ToDecimal(((string)DataGridView1.Rows[irow].Cells[0].Value).Trim(' ')) - 1 + ".jpg"



同样转换为十进制与转换为int不同,这是原始的。您的代码也非常脆弱,如果值不符合您的预期,则容易抛出异常。您应该使用int.TryParse而不是Convert.ToDecimal。谷歌的使用。


Also converting to decimal isn't the same as converting to int which is what the original did. Your code is also very fragile and prone to throwing an exception if values are not what you expect. You should use int.TryParse rather than Convert.ToDecimal. Google for usage.