gpt4 book ai didi

c# - 从 asp :CheckBoxList with Datasource 计算多个值的总和

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:51 25 4
gpt4 key购买 nike

我有以下 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" />

用户可以从复选框列表中选择多个选项。 cats_pointsDataValueField 是一个 int。在本例中,它们的值都为 20DropDownList 控件中的 cats_points_total 是另一个 int 值,它链接用户可以从中选择的最大总数。在本例中为 120

然后我有以下 C#

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 中做了多少选择,我都会得到 cattotal =120 catselected =20 catcalc =100 的输出。

我选择 2 个值的预期结果,每个值的值为 20;

cattotal =120 catselected =40 catcalc =100.

目前,除了 catselected,一切似乎都正常,计算 CheckBoxList 控件的总值。任何帮助将不胜感激。

最佳答案

为什么要对值进行两次解析(即使用 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 + ".";
}

关于c# - 从 asp :CheckBoxList with Datasource 计算多个值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33571370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com