[英]Parsing String: Input string was not in a correct format. #
I'm trying to run a stored procedure that is requiring an int to work correctly. 我正在尝试运行一个需要int才能正常工作的存储过程。 I pull an "ID" from a datagrid and then am trying to parse the int to allow the procedure to run, but am getting the error mentioned in the title.
我从数据网格中提取了一个“ ID”,然后尝试解析int以允许该过程运行,但出现标题中提到的错误。 Any thoughts on a better way to do this?
有更好的方法吗?
<asp:BoundColumn DataField="ID" Visible="true"></asp:BoundColumn>
<asp:Button ID="btnMarkComplete" Text="Mark Complete" runat="server" CommandArgument='<$# Eval("ID") %>' OnClick="BtnMarkCompleteClick"/>
</ItemTemplate>
int iD = Convert.ToInt32(d.CommandArgument.ToString());
In answer to your question, "is there a better way to do this"? 在回答您的问题时,“是否有更好的方法来做到这一点”?
Yes, and it's called TryParse
: 是的,它叫做
TryParse
:
int iD = 0;
if(Int32.TryParse(d.CommandArgument.ToString(), out iD))
{
// Do something with iD
}
Explanation 说明
You're implying (using a basic Convert
method) that the input can be converted to an Int32
, which is why you get an exception when it can't. 你暗示(使用基本的
Convert
方法),该输入可转换成Int32
,这就是为什么你会得到一个异常时,它不能。 With the way I've suggested above, you're simply trying to parse it. 使用上面我建议的方法,您只是在尝试解析它。
TryParse
returns a boolean
you can then evaluate to decide on a path of execution. TryParse
返回一个boolean
您可以评估该boolean
值以确定执行路径。
There's a typo there to start: 有一个错别字开始:
<$# Eval("ID") %>
Should be 应该
<%# Eval("ID") %>
So you are trying to convert the string value <$# Eval("ID") %>
to an integer which will fail and throw the error you are receiving. 因此,您正在尝试将字符串值
<$# Eval("ID") %>
转换为整数,该整数将失败并引发收到的错误。 The field won't bind to ID because of the typo. 由于输入错误,该字段不会绑定到ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.