C# 方法“ToString”没有重载需要 1 个参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9091177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:51:58  来源:igfitidea点击:

no overload for method "ToString" takes 1 arguments

c#asp.netsql

提问by user1125911

I have a data reader to read the datas from database. I am reading TotalPrice from sales table. I would like to show the total price as 2 decimal place.

我有一个数据阅读器可以从数据库中读取数据。我正在从销售表中读取 TotalPrice。我想将总价显示为小数点后两位。

The code is something link that:

该代码是一些链接:

TotalPrice.Text = myReader["TotalPrice"].ToString("N2");

However i encounted this error: no overload for method "ToString" takes 1 arguments What's wrong with the code?

但是我遇到了这个错误:方法“ToString”没有重载需要1个参数代码有什么问题?

采纳答案by Chris Shain

Assuming that TotalPrice is a Decimal column, and that myReader is a DataReader:

假设 TotalPrice 是一个 Decimal 列,而 myReader 是一个 DataReader:

TotalPrice.Text = myReader.GetDecimal(myReader.GetOrdinal("TotalPrice")).ToString("N2");

The idea here is that myReader's indexer (what you are using when you call myReader["TotalPrice"]) returns an Object. It has to, since it doesn't know at compile time what type the column is. By using .GetDecimal(), you are assuring that you get a Decimal value back, or an error.

这里的想法是 myReader 的索引器(您在调用 时使用的myReader["TotalPrice"])返回一个对象。它必须这样做,因为它在编译时不知道该列是什么类型。通过使用.GetDecimal(),您可以确保获得 Decimal 值或错误。

The .ToStringoverload that takes a format string is declared on Decimal, not on Object. Object's .ToStringtakes no arguments.

.ToString采用格式字符串的重载是在 Decimal 上声明的,而不是在 Object 上声明的。对象的 . ToString不接受任何争论。

The inner call to GetOrdinal returns the field's index given the name- if you are doing this in a loop for multiple data rows, you'd probably want to cache that in a variable.

对 GetOrdinal 的内部调用返回给定名称的字段索引 - 如果您在多个数据行的循环中执行此操作,您可能希望将其缓存在变量中。

回答by Despertar

String.Format() will do the trick. F2 is fixed-point notation with 2 decimal places.

String.Format() 可以解决问题。F2 是带有 2 个小数位的定点符号。

TotalPrice.Text = string.Format("{0:F2}", (double)myReader["TotalPrice"]);