C# Set combo item with selectedValue

前端 未结 6 697
生来不讨喜
生来不讨喜 2020-12-11 03:55

I am dynamically creating a combobox like this:

public Control GenerateList(Question question)
{
    // Get a list with answer possibilities
    List

        
相关标签:
6条回答
  • 2020-12-11 04:13
    cmb.SelectedIndex = cmb.FindStringExact("Desired Value")
    

    The cmb.FindStringExact("Desired String") returns the index of the value you would like to select and the cmb.SelectedIndex sets the combobox to that index.

    Thanks to Billious for showing me the light!

    FYI - This is the VB.NET Winforms Version.

    0 讨论(0)
  • 2020-12-11 04:13

    I ran into the same problem, and found that my issue was I was treating SelectedValue as an integer, when in actual fact it was an object. The "FindByValue" solution from Danny Chen above doesn't work in WinForms, so I tried using "FindStringExact" and searched on the DisplayMember:

    cmb.Items.FindStringExact(<Display string>)
    

    Not an ideal solution, but it worked.

    0 讨论(0)
  • 2020-12-11 04:14

    I met this weird issue before, at last I gave up and used another way:

    cmb.Items.FindByValue(givenAnswers[0].AnswerId).Selected = true;
    

    It worked fine...Hope you good luck!

    0 讨论(0)
  • 2020-12-11 04:19

    Are you looking at the same property?

     cmb.ValueMember = "Id"; 
     ..
     cmb.SelectedValue = givenAnswers[0].AnswerId; 
    

    You're refering to another ValueMember then the Id you're posting into the SelectedValue. Besides that you might want to try to set your Display- and Value-member before databinding. It's faster.

    0 讨论(0)
  • 2020-12-11 04:22

    Make sure QuestionAnswer has public accessors corresponding (same name) to the Display/Value Members you use.

    0 讨论(0)
  • 2020-12-11 04:23

    Solution:

    The SelectedValue, SelectedIndex, SelectedItem properties can't be set until the control is added to the form. After the control is added to the form, the selectedValue, -Index and -Item properties can be set.

    0 讨论(0)
提交回复
热议问题