How do I bind a ComboBox so the displaymember is concat of 2 fields of source datatable?

后端 未结 7 1968
既然无缘
既然无缘 2020-12-01 18:03

I\'d like to bind a ComboBox to a DataTable (I cannot alter its original schema)

cbo.DataSource = tbldata;
cbo.DataTextField = \"Na         


        
相关标签:
7条回答
  • 2020-12-01 18:25

    The easiest way is to create a new calculated column in the DataTable, using the Expression property :

    tbldata.Columns.Add("FullName", typeof(string), "Name + ' ' + Surname");
    ...
    cbo.DataTextField = "FullName";
    
    0 讨论(0)
  • 2020-12-01 18:28

    Have a property in your class that is the concat of Name and Surname. And bind the DataTextField to this property.

    In case you are binding it to a DataTable, you can add a new column to the DataTable whose values are concat of Name and Surname and bind it to the combo.

    0 讨论(0)
  • 2020-12-01 18:35

    I would create a property on your data object then map that to the DataTextField

    Data Object

    public string FullName
    {
      get { return Name + " " + Surname; }
    }
    

    Code-behind

    cbo.DataSource = tbldata;
    cbo.DataTextField = "FullName";
    cbo.DataValueField = "GUID";
    cbo.DataBind();
    
    0 讨论(0)
  • 2020-12-01 18:36

    Or implement 'Format' event like this:

    DataRow r = ((DataRowView)e.ListItem).Row;
    e.Value = r[ "FirstName" ] + " - " + r[ "LastName" ];
    
    0 讨论(0)
  • 2020-12-01 18:39

    Have a look at calculated columns using the Expression property of DataColumn.

    0 讨论(0)
  • 2020-12-01 18:45

    You can register the combo binding event and iterate the items, setting each item text to the desired fields using the combobox item data item.

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