问题描述
本质上是尝试在复选框被选中时捕获信息,如果是,则捕获输入的数量。附上代码。
<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>");
}