[英]Choose ComboBox value and convert it into a int
我有一个值为4、5、6、7、8、9、10、11、12的ComboBox,当我选择其中一个数字时,我想将选择的数字转换为Integer,以便将其用于其他功能。
代码如下:
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selected = this.comboBox1.GetValue(this.comboBox1.SelectedItem);
int N = Int32.Parse(selected.Text);
}
问题是我通过this.comboBox1.GetValue
GetValue收到错误this.comboBox1.GetValue
。
您可以通过执行以下操作从ComboBox中获取价值
int N = Int32.Parse(this.comboBox1.SelectedItem.ToString());
使用TryParse: https ://msdn.microsoft.com/zh-cn/library/f02979c7( v= vs.110).aspx ? cs-save-lang =1& cs-lang = csharp#code-snippet-2
bool result = Int32.TryParse(this.combobox.text, out int n);
if (result)
{
Console.WriteLine("Converted number!);
// n is now an int!
}
else
{
Console.WriteLine("Not a valid number")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.