Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

c# - 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. 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());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...