Question

I have a BO called Agent and another called AgentList that is defined as:

Inherits ComponentModel.BindingList(Of Agent)  

Agent list contains a method called "CreateAgentList" that returns a AgenteList object populated from DB.

To populate a combobox and bind it I use the following code:

    cmbAgent.DataSource = AgenteList.CreateAgentList()
    cmbAgent.DisplayMember = "AgentCode"
    cmbAgent.ValueMember = "Id"
    cmbAgent.DataBindings.Add(New Binding("ValueMember", AgenteBindingSource, 
         "AgenteDiRiferimento", False, DataSourceUpdateMode.OnPropertyChanged))

How can I have a no-text first item in the combobox associated to Null value member?

N.B. The purpose is to let the user not chose any Agent. ReferenceAgent field in DB is a Nullable Integer FK to the Agent table. The bind is used to display the correct agent every time a user surf in the agents list and the program loads the data of the selected Agent in the form.

Was it helpful?

Solution

Besides than storing null values in the Agent field of the DB I just dropped the FK that wasn't mandatory being the input of the combobox already driven and not letting the user put wrong info and replacing the "null id" with 0 (my Id field is an identity that starts from 1, so there're no problems doing it).

The code to populate my combobox and to bind it during form loading is the following:

    Dim cmb_Items As New Dictionary(Of Integer, String)
    cmb_Items.Add(0, "")

    For Each item As Agent In AgentList.CreateAgentList()
        cmb_Items.Add(item.Id, item.AgentCode)
    Next

    cmbAgent.DataSource = New BindingSource(cmb_Items, Nothing)
    cmbAgent.ValueMember = "Key"
    cmbAgent.DisplayMember = "Value"
    cmbAgent.DataBindings.Add(New Binding("SelectedValue", AgentBindingSource, "Agent", False, DataSourceUpdateMode.OnPropertyChanged))

Not exactly the solution I had in mind in first place, but it works like a charm!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top