how to pass Enum

  • Thread starter Thread starter kjqua
  • Start date Start date
K

kjqua

Hi all,

I am newbie in c# and i have a question.

I try to work with serial port.
and i will like to configure the serial port by a form

I add in a ComboBox.parity some items like:
None
Odd
Even
Mark
Space

then i will like to pass the item value to serialPort.parity
serialPort.parity = cmbParity.SelectedItem
how can i do ?

thanks
Marco
 
kjqua said:
I add in a ComboBox.parity some items like:
None
Odd
Even
Mark
Space

then i will like to pass the item value to serialPort.parity
serialPort.parity = cmbParity.SelectedItem
how can i do ?

You can convert text into enum values using the static method Enum.Parse:

serialPort.parity = Enum.Parse(typeof(System.IO.Ports.Parity),
cmbParity.SelectedItem);
 
Alberto Poblacion said:
You can convert text into enum values using the static method Enum.Parse:

serialPort.parity = Enum.Parse(typeof(System.IO.Ports.Parity),
cmbParity.SelectedItem);

Enum.Parse returns object, you still need a cast:

serialPort.Parity =
(System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity),
cmbParity.SelectedItem);
 
Ben Voigt [C++ MVP] ha scritto:
Enum.Parse returns object, you still need a cast:

serialPort.Parity =
(System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity),
cmbParity.SelectedItem);
Hi,
I try both code but they don't work
i have this message error
The best overloaded method match for 'System.Enum.Parse(System.Type,
string)' has some invalid arguments
Argument '2': cannot convert from 'object' to 'string'
 
kjqua said:
I try both code but they don't work
i have this message error
The best overloaded method match for 'System.Enum.Parse(System.Type,
string)' has some invalid arguments
Argument '2': cannot convert from 'object' to 'string'

So cast cmbParity.SelectedItem to a string in the call...
 
Jon Skeet [C# MVP] ha scritto:
So cast cmbParity.SelectedItem to a string in the call...

Thanks now it work
serialPort.Parity =
(System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity),
cmbParity.SelectedItem.ToString());


marco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top