从列表框项中提取数字

时间:2014-02-24 13:11:08

标签: c# listbox

我是编程新手,无法找到从列表框中取回数字的方法。

我正在尝试从列表框中的选定项目中提取一个数字。

列表框中的信息类型为“旅行:2013年12月3日15.66欧元。

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();
}

由于

5 个答案:

答案 0 :(得分:1)

您可以使用Regex上的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;


        }

答案 1 :(得分:0)

获得所需数量/价格的简便方法是使用拆分:

var inputDataParts = inputdata.Split(' ');

现在第二部分应该是价格

string price = inputDataParts[1];

现在摆脱欧元符号并修剪它:

price = price.Replace('€', '').Trim();

现在价格应该保持“15.66” - 如果需要可以转换它。

更难的方法是使用RegEx。

答案 2 :(得分:0)

您可以使用这样的正则表达式(查看如何使用正则表达式http://msdn.microsoft.com/fr-fr/library/0z2heewz(v=vs.110).aspx):

string pattern = @"[0-9]+(\.[0-9]+)? ";

然后,您只需将匹配的字符串转换为double:

double value = Convert.ToDouble(matchedString);

答案 3 :(得分:0)

试试这个:

string str = listBox1.SelectedItem.ToString();
int startIndex = str.IndexOf('€');
str = str.Substring(startIndex+1).Split(' ')[0].Trim();
decimal value = Convert.ToDecimal(str);

答案 4 :(得分:0)

我建议你创建费用等级:

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());
    }
}

然后将列表框绑定到费用对象列表 - 它们将以Travel: €15.66 on 12/3/13格式显示:

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;

获取所选费用的金额很容易,因为所选项目将是Expense对象:

var expense = (Expense)listBox1.SelectedItem;
// expense.Amount

注意:您可以创建一些将返回格式化字符串的ToString()Display属性,而不是覆盖Description功能,并将此属性指定为listBox的DisplayMember名称。