Parsing String: Input string was not in a correct format. #

笑着哭i 提交于 2020-01-17 16:30:19

问题


I'm trying to run a stored procedure that is requiring an int to work correctly. 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. 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());

回答1:


In answer to your question, "is there a better way to do this"?

Yes, and it's called 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. 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.




回答2:


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. The field won't bind to ID because of the typo.



来源:https://stackoverflow.com/questions/27319267/parsing-string-input-string-was-not-in-a-correct-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!