我有以下asp.net代码
<asp:DropDownList ID="cat_points_total" runat="server" DataSourceID="semester1"
DataTextField="cats_points_total" DataValueField="cats_points_total"
Visible="true"></asp:DropDownList>
<asp:CheckBoxList ID="module_semester_1" runat="server" DataSourceID="semester1"
DataTextField="module_name" DataValueField="cats_points"></asp:CheckBoxList>
<asp:Label ID="sem_1_fb" runat="server" Text=""></asp:Label>
<asp:Button ID="sem_1_cat" runat="server" Text="Test" OnClick="sem_1_cat_Click" />
用户可以从复选框列表中选择多个选项。 DataValueField
的{{1}}是一个int。在这种情况下,它们的值都为cats_points
。 20
控件中找到的cats_points_total
是另一个int值,用于链接用户可以选择的最大总数。在这种情况下,它是DropDownList
。
然后我有以下C#
120
目前,无论我在protected void sem_1_cat_Click(object sender, EventArgs e)
{
for (int i = 0; i < module_semester_1.Items.Count; i++)
{
if (module_semester_1.Items[i].Selected)
{
string value = module_semester_1.Items[i].Value;
int cattotal;
cattotal = Convert.ToInt32(cat_points_total.SelectedValue);
cattotal = int.Parse(cat_points_total.SelectedValue);
int catselected;
catselected = Convert.ToInt32(value);
catselected = int.Parse(value);
int catcalc;
catcalc = cattotal - catselected;
sem_1_fb.Visible = true;
sem_1_fb.Text = "cattotal =" + cattotal + " catselected =" +
catselected + " catcalc =" + catcalc + ".";
}
}
}
中做出多少选择,我都会获得CheckBoxList
的输出
我选择2个值的预期结果,每个值的值为20;
cattotal =120 catselected =20 catcalc =100.
在当前时间,除了cattotal =120 catselected =40 catcalc =100.
之外,一切似乎都有效,计算CheckBoxList控件的值总和。任何帮助将不胜感激。
答案 0 :(得分:3)
为什么要解析值两次(即使用Convert.ToInt32()
和int.Parse()
)?只做一个或另一个。无论如何,将变量声明移出循环并使用catselected
添加到+=
,否则您将使用每个新循环覆盖先前的值。
试试这个:
protected void sem_1_cat_Click(object sender, EventArgs e)
{
int catselected = 0;
for (int i = 0; i < module_semester_1.Items.Count; i++)
{
if (module_semester_1.Items[i].Selected)
{
string value = module_semester_1.Items[i].Value;
catselected += int.Parse(value);
}
}
int cattotal = int.Parse(cat_points_total.SelectedValue);
int catcalc = cattotal - catselected;
sem_1_fb.Visible = true;
sem_1_fb.Text = "cattotal =" + cattotal + " catselected =" +
catselected + " catcalc =" + catcalc + ".";
}