微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Gridview 无法解析输入字符串不正确

如何解决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);

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

解决方法

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

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

通过进一步的测试。我尝试使用 foreach 循环,它似乎有效。感谢您的帮助,这是我的解决方案

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。