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

后端 未结 7 1969
既然无缘
既然无缘 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:46

    The calculated column solution is probably the best one. But if you can't alter the data table's schema to add that, you can loop through the table and populate a new collection that will serve as the data source.

    var dict = new Dictionary<Guid, string>();
    foreach (DataRow row in dt.Rows)
    {
        dict.Add(row["GUID"], row["Name"] + " " + row["Surname"]);
    }
    cbo.DataSource = dict;
    cbo.DataTextField = "Value";
    cbo.DataValueField = "Key";
    cbo.DataBind();
    

    Obviously this isn't as performant as binding directly to the DataTable but I wouldn't worry about that unless the table has thousands of rows.

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