简体   繁体   English

如何从 c# 中的组合框获取浮动值

[英]How to get value as float from Combo box in c#

Please help me in this situation在这种情况下请帮助我

float sumofgradeintocradit = float.Parse(comboBox1.Text);

But an exception caught say "Input string was not in a correct format."但是捕获到一个异常,说“输入字符串的格式不正确。”

What is the problem please give me some solution I want to take an value from a combo box and store as an float.有什么问题请给我一些解决方案我想从组合框中获取一个值并将其存储为浮点数。

Instead of trying to convert display text back into a float, you can use a custom object, which allows holding values separate from the shown text.您可以使用自定义 object,而不是尝试将显示文本转换回浮点数,它允许将值与显示的文本分开。

Example:例子:

private class ComboItem
{
    public string ItemText  { get; set; }
    public float  ItemFloat { get; set; }

    public ComboItem(string itemText, float itemFloat)
    {
        this.ItemText  = itemText;
        this.ItemFloat = itemFloat;
    }

    public override string ToString()
    {
        return this.ItemText;
    }
}

private void AddItemsToComboBox
{
    comboBox1.Items.Add(new ComboItem("One Point Two", 1.2f));
    comboBox1.Items.Add(new ComboItem("Three Point Four", 3.4f));
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var selectedFloat = ((ComboItem)comboBox1.SelectedItem).ItemFloat;
    Debug.Print("Selected: " + selectedFloat);
}

This also works for other things like the ListView.这也适用于 ListView 等其他内容。

comboBox1.Text does not contain a flot in the right format. comboBox1.Text 不包含格式正确的浮点数。

For debugging Print / trace the value to confirm it.用于调试打印/跟踪值以确认它。

You can add a client side validation to make sure it is in the right format.您可以添加客户端验证以确保其格式正确。

After that if it is a client server app you can add a server side validation to handle the exceptions mentioned in the following MSDN and reprompt the user for input by using try parse or try catch.之后,如果它是客户端服务器应用程序,您可以添加服务器端验证来处理以下 MSDN 中提到的异常,并使用 try parse 或 try catch 重新提示用户输入。 http://msdn.microsoft.com/en-us/library/2thct5cb(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/2thct5cb(v=vs.110).aspx

Reference: Also see the following on parsing numeric stringshttp://msdn.microsoft.com/en-us/library/xbtzcc4w(v=vs.110).aspx参考:另请参阅以下关于解析数字字符串的内容 http://msdn.microsoft.com/en-us/library/xbtzcc4w(v=vs.110).aspx

If I were you I would try this:如果我是你,我会试试这个:

float sumofgradeintocradit ;
if (float.TryParse(comboBox1.Text, out _))
    sumofgradeintocradit = float.Parse(comboBox1.Text);

This checks to see if the combobox1.text is a valid float, and if so, it assigns the value to sumofgradeintocradit这将检查 combobox1.text 是否是有效的浮点数,如果是,它将值分配给sumofgradeintocradit

HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM