简体   繁体   English

C#ComboBox字符串值到对象变量到类?

[英]C# ComboBox String value to object variable to class?

I'm attempting to take a string value from a Combo box then pass it through an object variable to a class and store it there in a string variable. 我正在尝试从组合框中获取字符串值,然后将其通过对象变量传递给类,并将其存储在字符串变量中。

 private void cboTimeZone_SelectedValueChanged(object sender, EventArgs e)
 {
     extTime1.timeZone = cboTimeZone.SelectedItem;
 }

I'm not totally use to the combo box options to use so. 我并不完全习惯使用组合框选项。

Does the cboTimeZone contain string objects? cboTimeZone是否包含字符串对象? In this case, a simple cast should be enough if extTime1.timeZone is a string: 在这种情况下,如果extTime1.timeZone是一个字符串,那么简单的强制转换就足够了:

extTime1.timeZone = (string)cboTimeZone.SelectedItem

if cboTimeZone was filled with objects of type myObject , u can use the ToString() method on the item if you overwrote it in your myObject class: 如果cboTimeZone中填充了myObject类型的对象,那么如果在myObject类中重写了该对象,则可以在该项目上使用ToString()方法:

extTime1.timeZone = cboTimeZone.SelectedItem.ToString()

If you selected a specific property MyProperty of myObject to be shown in the combo box, you can first cast to the object and then access the property by using 如果选择了要显示在组合框中的myObject的特定属性MyProperty ,则可以首先强制转换为该对象,然后使用

extTime1.timeZone = ((myObject)cboTimeZone.SelectedItem).MyProperty

to get that property as a result. 从而获得该财产。

Hope that helps. 希望有所帮助。

It's not clear from your question whether your ComboBox is data-bound or not; 从你的问题不清楚你的ComboBox是否是数据绑定的; either way, I think it would be a good idea to first figure out if SelectedItem is indeed the correct property to use, or if there's another, more appropriate one. 无论哪种方式,我认为首先弄清楚SelectedItem是否确实是正确使用的属性,或者是否有另一个更合适的属性是一个好主意。

If you've set a DataSource for your ComboBox , you've probably also set a DisplayMember . 如果您为ComboBox设置了一个DataSource ,那么您可能还设置了一个DisplayMember In that case, the DisplayMember will determine which property of the currently selected item of the data source will be shown in the ComboBox as text. 在那种情况下, DisplayMember将确定数据源的当前选定项目的哪个属性将在文本ComboBox显示为ComboBox

If you've set a ValueMember , you can also use the SelectedValue property to retrieve that property of the currently selected data source item. 如果设置了ValueMember ,则还可以使用SelectedValue属性来检索当前所选数据源项的该属性。

SelectedItem simply retrieves the currently selected data source item. SelectedItem只检索当前选定的数据源项。 This may be a complex object, or a string object, or something else; 这可能是一个复杂的对象,也可能是一个字符串对象,或其他。 check with your data source. 检查您的数据源。

The ComboBox 's Text property simply contains the text that's currently displayed in the ComboBox 's text input field and has type string . ComboBoxText属性仅包含ComboBox的文本输入字段中当前显示的文本,其类型为string

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

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