【问题标题】:Gridview cannot parse input string is not correctGridview 无法解析输入字符串不正确
【发布时间】:2021-05-26 07:03:47
【问题描述】:

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

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

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

【问题讨论】:

  • edit 提出问题,以便准确显示失败的行并包含该行的数据。理想情况下,将代码缩短到包含硬编码数据的那一行(如int quantity = Convert.ToInt32("salmon");)。
  • 刚刚编辑了我的问题我很抱歉@AlexeiLevenkov

标签: c# asp.net gridview findcontrol


【解决方案1】:

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

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

【讨论】:

  • 谢谢你!代码甚至不会走那么远,因为将文本框转换为 int 时出错。不过,我很感谢您的意见!
  • 很高兴它有帮助。请记住在到期时给予信任并接受或至少支持帮助您解决问题的答案。在您的解决方案中,您所做的只是通过删除整数转换来避免异常。相反,您应该使用 Int32.Tryparse() 来执行类型转换,而不是使用 Convert.ToInt32,如果用户输入的不是数字,则会引发异常。
  • 我正在尝试,但我的声誉太低了
【解决方案2】:

通过进一步测试。我尝试使用 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>");
                    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多