简体   繁体   中英

bind combobox selectedvalue using enum

I failed to bind the combobox selectedvalue.

 public void InitializePage()
 {          
    cbStatus.DataSource = Enum.GetValues(typeof(CourseStudentStatus));
 }

on my constructor

 public EditCourseForm(int status)
 {
     InitializePage();                      
     cbStatus.SelectedText = Enum.GetName(
        typeof(CourseStudentStatus), status).ToString();         
 }

I have tried this too. cbStatus.SelectedValue = Status

but I'm not able to set SelectedValue on the ComboBox.

Update My enum

 public enum CourseStudentStatus
{
    Active = 1,
    Completed = 2,
    TempStopped = 3,
    Stopped = 4,
}

Problem is resolved.
cbStatus.SelectedItem = (CourseStudentStatus)status;

Hope it helps.

Have you tried

public EditCourseForm(CourseStudentStatus status)
{
    InitializePage();            

    cbStatus.SelectedItem= status;
}

Change your InitializePage() function code to this

public void InitializePage() {

    cbStatus.DataTextField = Enum.GetName(typeof(CourseStudentStatus));

    cbStatus.DataValueField = Enum.GetValues(typeof(CourseStudentStatus));
}

Updated Try with this.

var itemValues = Enum.GetValues(typeof(CourseStudentStatus)).Cast<CourseStudentStatus>().ToDictionary(obj => obj.ToString(), obj => obj.GetHashCode()).ToList();
        comboBox1.DisplayMember = "Key";
        comboBox1.ValueMember = "Value";
        comboBox1.DataSource = itemValues;

here itemValues is a type of List<KeyValuePair<string, int>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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