-1

我已将错误添加到此问题的标题中。

我收到以下代码错误。输入字符串的格式不正确。

错误发生在这一行:

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];

    }
}
4

2 回答 2

1

您需要将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") %>' />
于 2013-10-01T21:13:08.470 回答
0

假设从 string 转换为 int 时出错,请尝试:

const int DefaultIndexValue = 1;

int index;
if (!Int32.TryParse(e.CommandArgument.ToString(), out index))
{
    index = DefaultIndexValue;
}
于 2013-10-01T20:56:30.270 回答