使用按钮在文本框中添加列表框 [英] Adding Listbox in textbox using button
本文介绍了使用按钮在文本框中添加列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨
我有一个列表框和文本框
我需要在列表框中添加所有值的总和,然后在包括文本框值的文本框中发布总计.
技术-使用Windows窗体的C#.net
Hi
I have a listbox and textbox
I need to add the sum of all values in a listbox and post the total in a textbox including textbox value.
Technology - C#.net using windows form
推荐答案
此处是操作方法:
Here is how to do it:
static int Sum(ListBox listBox) {
int result = 0;
for (int index = 0; index < listBox.Items.Count; ++index) {
int value;
if (!int.TryParse(listBox.Items[index], out value)) continue;
result += value;
}
return result;
}
//...
int sum = 0;
//what does it mean "including text box value"?
//perhapse, this (optional):
int textBoxValue = 0;
int.TryParse(MyTextBox.Text, out textBoxValue);
sum += textBoxValue;
sum += Sum(MyListBox);
MyTextBox.Text = sum.ToString());
如果数字类型不是int
,则相应地更改代码(使用double
或Sum
中的任何内容).
If the numeric type if not int
, changes the code accordingly (use double
or whatever in Sum
).
这样做:
Do it like this :
double total=0;
foreach (object item in listBox1.Items)
{
total += (double)item;
}
txtTotal.Text = total.ToString();
或者如果您将值作为字符串,则使用double.Parse(item)
而不是 (double)item
.
or if you have the values as string, then use double.Parse(item)
instead of (double)item
.
另一种方法是,您可以使用泛型并在一行中执行
喜欢
Another way is u can use Generics and do this in a single line
Like
int total = ListBox1.Items.Cast<listitem>().Select<listitem,>(s => Convert.ToInt32(s.Text)).Aggregate((a, b) => a + b);
</listitem>
但根据KIM TOGO的介绍,简短而甜美
but as per KIM TOGO, the short and sweet
ListBox1.Items.Cast<listitem>().Sum(item => int.Parse(item.Text));</listitem>
这篇关于使用按钮在文本框中添加列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文