首页 > 解决方案 > Gridview 无法解析输入字符串不正确

问题描述

本质上是在选中复选框时尝试捕获信息,如果是则捕获输入的数量。附上代码。

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

这是我的 aspx.cs 代码。

 //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>");
        }
    }
}

给出错误的行是这一行

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

错误:输入字符串的格式不正确

标签: c#asp.netgridviewfindcontrol

解决方案


即使文本框留空,测试if (Tbox == null)也永远不会为真,因为您检查的是对文本框的引用,而不是其内容。我相信你的测试应该是:

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

推荐阅读