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

最新更新