简体   繁体   中英

Gridview cannot parse input string is not correct

Essentially trying to capture information when a checkbox is checked off, if it is then capture the quantity inputted. Attached is the code.

  <asp:TemplateField HeaderText="Quantity">
        <ItemTemplate>
            <asp:TextBox ID="TextboxQuantity" runat="server"></asp:TextBox>
        </ItemTemplate>
  </asp:TemplateField>
</Columns>

Here is my aspx.cs code.

 //check to see if a check box is checked
for (int row = 0; row < gv_Input.Rows.Count; row++)
{

    CheckBox Cbox = (CheckBox)gv_Input.Rows[row].FindControl("CheckboxSelect");
    TextBox Tbox = (TextBox)gv_Input.Rows[row].FindControl("TextboxQuantity");
    int quantity = Convert.ToInt32(Tbox.Text);
    if (Cbox.Checked)
    {
        if (Tbox == null)
        {
            Response.Write("<script>alert('Fill in textbox')</script>");
        }
        else
        {
            Response.Write(
              "<script>alert('Something was inputted into the textbox')</script>");
        }
    }
}

The line that gives the error is this line

int quantity = Convert.ToInt32(Tbox.Text);

Error: Input string was not in the correct format

Even if the text box is left blank, the test if (Tbox == null) is never going to be true because you are checking the reference to the text box, not its content. I believe that your test should be:

if(Tbox == null || string.IsNullOrWhitespace(Tbox.Text) == true) {

Through further testing. I attempted using a foreach loop and it seemed to work. Thank you for you help here is my solution

foreach (GridViewRow row in gv_Input.Rows)
            {

                CheckBox Cbox = (CheckBox)row.FindControl("CheckboxSelect");
                TextBox Tbox = (TextBox)row.FindControl("TextboxQuantity");
                if (Cbox.Checked)
                {
                    if (Tbox.Text == null || string.IsNullOrEmpty(Tbox.Text) == true)
                    {
                        Response.Write("<script>alert('Fill in textbox')</script>");
                    }
                    else {
                        Response.Write("<script>alert('Successful find')</script>");
                    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM