C# 从列表框项目中提取数字
我是编程新手,无法找到从列表框中获取数字的方法 我正试图从列表框中的选定项中提取一个数字 列表框中的信息类型为“2013年3月12日的差旅:15.66欧元”C# 从列表框项目中提取数字,c#,listbox,C#,Listbox,我是编程新手,无法找到从列表框中获取数字的方法 我正试图从列表框中的选定项中提取一个数字 列表框中的信息类型为“2013年3月12日的差旅:15.66欧元” private void btnRemove_Click(object sender, RoutedEventArgs e) { decimal inputdata = (decimal)lbxDisplay.SelectedItems; //Remove selected items from Listbox l
private void btnRemove_Click(object sender, RoutedEventArgs e)
{
decimal inputdata = (decimal)lbxDisplay.SelectedItems;
//Remove selected items from Listbox
lbxDisplay.Items.RemoveAt(lbxDisplay.SelectedIndex);
//Update Expenses Total text block
tblkTotal.Text = string.Format("Total Expenses\t{0}", expense.DeductedTotal();
}
谢谢获取所需数量/价格的简单方法是使用拆分:
var inputDataParts = inputdata.Split(' ');
现在第二部分应该是价格
string price = inputDataParts[1];
现在,摆脱欧元符号并对其进行修整:
price = price.Replace('€', '').Trim();
现在价格应该保持在“15.66”的水平,如果需要的话可以转换
更难的方法是使用正则表达式。您可以使用
SelecteItem
上的正则表达式来提取数字
private void button1_Click_1(object sender, EventArgs e)
{
var sel = listBox1.SelectedItem;
Regex reg = new Regex(@"[0-9\.]+");
var res = reg.Match(sel.ToString());
//if you want to compute the total
double total = 0;
var allItems = listBox1.SelectedItems;
foreach (var item in allItems)
{
double dres = double.Parse(reg.Match(sel.ToString()).Value);
total = dres + total;
}
tblkTotal.Text = string.Format("Total Expenses\t{0}", total);
}
如果您想要的是SelectedItems的总数,而不仅仅是一项,那么只需要一个技巧,您就可以在表单的构造函数中执行类似的操作
public Form1()
{
InitializeComponent();
listBox1.SelectionMode = SelectionMode.MultiExtended;
}
您可以使用这样的正则表达式(查看此处以了解如何使用正则表达式):
然后,只需将匹配的字符串转换为双精度:
double value = Convert.ToDouble(matchedString);
试试这个:
string str = listBox1.SelectedItem.ToString();
int startIndex = str.IndexOf('€');
str = str.Substring(startIndex+1).Split(' ')[0].Trim();
decimal value = Convert.ToDecimal(str);
我建议您创建费用类别:
public class Expense
{
public Expense(string name, decimal amount, DateTime date)
{
Name = name;
Amount = amount;
Date = date;
}
public string Name { get; private set; }
public decimal Amount { get; private set; }
public DateTime Date { get; private set; }
public override string ToString()
{
return String.Format("{0}: €{1} {2}",
Name, Amount, Date.ToShortDateString());
}
}
然后将列表框绑定到费用对象列表-它们都将在2013年3月12日以差旅:15.66欧元的格式显示:
var expenses = new List<Expense> {
new Expense("Travel", 16.5M, new DateTime(2013, 12, 3)),
new Expense("Sports", 13.0M, new DateTime(2013, 12, 4)),
};
listBox1.DataSource = expenses;
注意:您可以创建一些Display
或Description
属性来返回格式化字符串,而不是覆盖ToString()
功能,并将此属性指定为列表框的DisplayMember
名称。如果列表框中的信息是“12/3/13旅行:15.66欧元”,是否要“15.66”“仅限?@JohnnyC您为什么想要它?您只是删除了项目,您甚至没有使用该值,因为它是删除功能?我有一个总开支,必须向下修订,因为项目已从列表中删除。
var expenses = new List<Expense> {
new Expense("Travel", 16.5M, new DateTime(2013, 12, 3)),
new Expense("Sports", 13.0M, new DateTime(2013, 12, 4)),
};
listBox1.DataSource = expenses;
var expense = (Expense)listBox1.SelectedItem;
// expense.Amount