Search code examples
c#visual-studiocombobox

In the Designer in Visual Studio 2022, how to select the DataSource of a ComboBox?


In the Designer in Visual Studio 2022, how to select the DataSource of a ComboBox that is previously coded as:

var usersOffer = UserStorage.GetAllUsers();

var usersOfferOrderBy = usersOffer.OrderBy(alg => alg.CreatedAt).ToList();

var usersOfferBindingList = new BindingList<User>(usersOfferOrderBy);

Yes, I know what can be used:

userMainComboBox.DataSource = usersOfferBindingList;

userMainComboBox.DisplayMember = “Name”;

userMainComboBox.ValueMember = “Id”;

But I'm interested in doing this through the designer in Visual Studio 2022.

If you select the DataSource property of the ComboBox, there is no way to select usersOfferBindingList from the code.


Solution

  • The reason why the designer cannot read your BindingSource is that you only define it in the code. If you want to complete all the operations in the designer, you need to define a BindingSource in the designer.

    If you want to bind the data source directly from the designer, first of all, you need to create a new data source of the corresponding class in the designer.

    1、Select “Add Project Data Source” and then chose Object

    enter image description here

    2、 Select the corresponding class.

    enter image description here

    3、After created a BindingSource, bind the data source in the designer and select the display member.

    enter image description here

    4、After that, you just need to load the data from your data source when the Form.Load event is triggered.

    enter image description here

    After running, the combobox can display the data you need to show from the user normally.