I'开发者_如何转开发m getting the value of in an enum variable but while assigning it to another variable of type enum its getting 0 all the time...Here's the code i'm using , dbProperties is the object of class DBProperties which has a member of type DBType. dbProperties.DBType is always returning 0 even after assigning a value to it...Please help...!
DBType val = (DBType)cbDataType.SelectedIndex;
cbDataType.SelectedIndex = (int)val;
dbProperties.DBType = val;
This works fine for me. I think you've got a form in which you've got a dropdown combobox with items in it. So I replicated that and here is the code. The dropdown is populated with items that match (in as far as sequence) those shown in code below (the enum DBType) and shown in the first image attached
enum DBType { Int, Double, Float, Bool, String }
class DBProperties
{
private DBType dbType;
public DBType DBType { get { return dbType; } set { dbType = value; } }
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cbDataType_SelectedIndexChanged(object sender, EventArgs e)
{
DBType val = (DBType)cbDataType.SelectedIndex;
cbDataType.SelectedIndex = (int)val;
var dbProperties = new DBProperties();
dbProperties.DBType = val;
}
}
the dbProperties.DBType property is correctly set to the item selected in the dropdown.
On selecting "bool" in the dropdown the property is set to "Bool" as shown in the second image.
So dbProperties.DBType is the name of a variable which is of type DBType?
Not sure why it would be always returning 0 but I don't think it's anything to do with assigning values to enums.
Run this code for example:
enum DBType
{
Int,
Bool,
String
}
class DBProperties
{
public DBType DBType;
}
class Program
{
static void Main(string[] args)
{
DBType d = (DBType)2;
DBProperties p = new DBProperties();
p.DBType = d;
Console.WriteLine((int)p.DBType); //outputs 2
Console.ReadLine();
}
}
You need to be much more clear and specific with your question in order for people to help you.
Are you sure val
is not always zero? If you always select the first choice in the drop down box, selectedIndex will always be zero.
精彩评论