如何在C#中使用trim for datagrid? [英] How do I use trim for datagrid in C#?

查看:68
本文介绍了如何在C#中使用trim for datagrid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



我得到一个

Hello,

I am getting an

'object' does not contain a definition for 'Trim' and no extension method 'Trim' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

错误就行了:



error on this line:

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





这是Visual Basic的转换代码,如下所示:



It is a converted code from Visual Basic that goes like this:

SourcePageFile = SourceFolder & "\pg-" & CInt(Trim(DataGridView1.Rows(irow).Cells(0).Value)) - 1 & ".jpg"





如何成功执行语法以消除此错误?



请帮忙。



问候

Aman Chaurasia



我尝试过:



我尝试过以下方法:





How do I successfully execute the syntax to get rid of this error?

Please help.

Regards
Aman Chaurasia

What I have tried:

I have tried the following:

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







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







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







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

推荐答案

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

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.


这篇关于如何在C#中使用trim for datagrid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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