错误:输入字符串的格式不正确
本文关键字:格式 不正确 字符串 输入 错误 | 更新日期: 2023-09-27 18:33:27
我已将错误添加到此问题的标题中。
我收到以下代码的错误。 输入字符串的格式不正确。
错误发生在以下行:
int index = Convert.ToInt32(e.CommandArgument.ToString());
如何解决此错误?
aspx 页:
<asp:Content ID="MyMainPage" ContentPlaceHolderID="MMain" Runat="Server">
<div id="awindow" >
<asp:Panel ID="Panel1" runat="server" CssClass="main">
<div style="width: 100%; float: left">
<asp:TextBox runat="server" style="margin-left:5px; float:left;" ID="newauthor" />
<asp:ImageButton runat="server" ID="addauthor" Height="17px" ToolTip="Add a new author" ImageUrl="~/siteimages/Addbuttons/add.png" OnClick="AddAuthor_Click"/>
<asp:TextBox runat="server" ID="txtAuthor" Text='<%# Bind("Author") %>' />
<asp:Button ID="btnFindAuthor" runat="server" Text="Author Quick Find" CommandName="Select" OnCommand="btnFindAuthor_Click" />
<ajaxToolkit:AutoCompleteExtender ID="authors" runat="server" DelimiterCharacters="" Enabled="True" ServicePath="~/WebServices/authorsearchdisplay.asmx" ServiceMethod="AutoComplete" TargetControlID="authors" MinimumPrefixLength="3" />
</div>
<asp:SqlDataSource runat="server" ID="sqlAuthors" ConnectionString="<%$ ConnectionStrings:Libro %>" ProviderName="<%$ ConnectionStrings:Libro.ProviderName %>"
SelectCommand="SELECT * FROM Authors"
InsertCommand="authors_GetOrCreate" InsertCommandType="StoredProcedure">
<InsertParameters>
<asp:ControlParameter ControlID="newAuthor" Name="authorame" />
</InsertParameters>
</asp:SqlDataSource>
<asp:GridView runat="server" ID="gvAuthors" DataSourceID="sqlAuthors" DataKeyNames="AuthorID" AutoGenerateColumns="false">
<Columns>
<asp:HyperLinkField HeaderText="Author Name" DataNavigateUrlFormatString="~/authors.aspx?id={0}" DataNavigateUrlFields="AuthorID" DataTextField="AuthorName" />
</Columns>
</asp:GridView>
</asp:Panel>
</div>
<div>
</div>
</asp:Content>
脚本:
protected void btnFindAuthor_Click(object sender, CommandEventArgs e)
{
if (e.CommandName == "Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument.ToString());
// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = gvAuthors.Rows[index];
}
}
你需要将 CommandArgument 分配给按钮。
否则,int index = Convert.ToInt32(e.CommandArgument.ToString());
将引发异常。
例如-
<asp:Button ID="btnFindAuthor" runat="server" Text="Author Quick Find"
CommandName="Select"
OnCommand="btnFindAuthor_Click"
CommandArgument='<%# Bind("ID") %>' />
假设从字符串转换为 int 时出错,请尝试:
const int DefaultIndexValue = 1;
int index;
if (!Int32.TryParse(e.CommandArgument.ToString(), out index))
{
index = DefaultIndexValue;
}