DataSource DisplayMember with custom string composed of DataSource properties - c#

Is it possible to bind a ListBox to a DataSource of List<A>, while setting the DisplayMember to a custom string composed of A's properties, such as the following $"{A.b} {A.c}"?
var list1 = new List<A>();
// populate list
MyListBox.DisplayMember = $"{A.b} {A.c}"; // not going to work
MyListBox.DataSource = list1;
I know I can use an anonymous type, but I want the ListBox.Items to remain of type A. I don't want to do the following,
var list2 = (from a in list1
select new {A = a, DisplayMember = $"{a.b} {a.c}"}).ToList();
MyListBox.DisplayMember = "DisplayMember";
MyListBox.DataSource = list2;
because now MyListBox.Items is anonymous and A can't be retrieved like var list = MyListBox.Items.OfType<A>().
So, is there any way to do that?

I was thinking about it wrong. Solved it now. Maybe it was obvious to some, but I'm going to post my answer for posterity.
Use the anonymous type in the second example, and just set the ValueMember to A
var list2 = (from a in list1
select new {A = a, DisplayMember = $"{a.b} {a.c}"}).ToList();
MyListBox.DisplayMember = "DisplayMember";
MyListBox.ValueMember = "A";
MyListBox.DataSource = list2;
var list3 = MyListBox.Items.OfType<A>().ToList(); // works!

Related

why AutoComplete toolkit not updated with new items?

I set Datasource of toolkit:AutoCompleteBox to a list of string items. it work good but when I want add a new item to list then set again the list to Datasource of toolkit:AutoCompleteBox , it is not added.
I think Datasource of toolkit:AutoCompleteBox is not updated.
have you any idea on how to add a new item ? or refresh or update list?
List<string> c1 = new List<string>();
//... add some items to c1
txt11.ItemsSource = c1;
c1.Add(txt11.Text.Trim());
txt11.ItemsSource = c1;
Oh my GOD, i found problem easy with this code:
i have to assignment again. first time give null to AutoCompleteBox.
List<string> c1 = new List<string>();
//... add some items to c1
txt11.ItemsSource = c1;
c1.Add(txt11.Text.Trim());
txt11.ItemsSource = null;
txt11.ItemsSource = c1;

DevExpress LookUp repository item binded to dictionary set members

I have created a dictionary with an int key and a string value. I managed to set the dictionary as the datasource of my LookUp field. The lookup field is a repository item in a devexpress GridControl. The dictionary values are shown in my LookUp but I want to set the display and value member (and the caption) and don't know how to do this. Below you can see the current situation.
The dictionary code:
Dictionary<int, string> IncIncControls = new Dictionary<int,string>()
{
{ 1, "IncIncidentId"},
{ 2, "IncIncidentType"},
{ 3, "IncIncidentPriority"}
};
And the code to set the LookUp source
pageFieldLookUp.DataSource = (from d in IncIncControls
orderby d.Value
select new
{
d.Key,
d.Value
}).ToList();
How to modify the code to set lookup source in a way that I can set the display member/value member and caption. Or is there another (better) way to do this?
You can simply use RepositoryItemLookUpEditBase.DisplayMember and RepositoryItemLookUpEditBase.ValueMember properties for set display and value members, and use RepositoryItemLookUpEdit.Columns property to set captions:
pageFieldLookUp.DataSource = (from d in IncIncControls
orderby d.Value
select new
{
d.Key,
d.Value
}).ToList();
pageFieldLookUp.ValueMember = "Key";
pageFieldLookUp.DisplayMember = "Value";
pageFieldLookUp.PopulateColumns();
pageFieldLookUp.Columns[0].Caption = "Key caption";
pageFieldLookUp.Columns[1].Caption = "Value caption";

Manually Populating and Selecting ComboBox Items

I can't believe how difficult this simple task is.
I have the following code:
cboCountry.ValueMember = "ID";
cboCountry.DisplayMember = "Title";
var countries = from c in context.Set<sc_Countries>()
orderby c.Title
select new { c.ID, c.Title };
Now, I want to populate the ComboBox cboCountry with this collection, and then I want to select the list item with the ID (value) "US".
I was able to add the items to the ComboBox using cboCountry.Items.AddRange(countries.ToList()), but then cboCountry.SelectedValue = "US" had no effect.
Next, I tried adding the collection using cboCountry.DataSource = countries but this just left the control list empty.
Surely there must be a simple way to accomplish this trivial task. Can anyone offer the missing ingredient?
Until you call ToList() on your LINQ statement, you're not actually getting data from the database:
var countries = (from c in context.Set<sc_Countries>()
orderby c.Title
select new { c.ID, c.Title }).ToList();
Now you should be able to set the DataSource, etc. like you were:
cboCountry.ValueMember = "ID";
cboCountry.DisplayMember = "Title";
cboCountry.DataSource = countries;
cboCountry.SelectedValue = "US"
Edit:
Now that I'm re-reading your question, it looks like you were already calling countries.ToList(), but using Items.AddRange. I see the same thing you do when I try it. It appears you have to set the DataSource instead of using Items.AddRange, for SelectedValue to work.

gridview with arraylist not showing data

I have a gridview that I populate with values I get from a powershell command. For example my powershell command is get-command. I know the command returns the values. Here is my code however my gridview never shows the data.
ArrayList boxesarray = new ArrayList();
foreach (PSObject ps in commandResults)
boxesarray.Add(ps.Properties["Name"].Value.ToString());
boxes.DataSource = boxesarray;
boxes.DataBind();
I know the value is there because I replaced the last two lines with a label and was able to see the value.
boxlabel.text = boxesarray[4];
I must be missing something. Help please.
The GridView requires a collection or IEnumerable of classes which have properties, and the properties are mapped to columns.
An array like yours have value typed objects (strings) which has no roperties, so you can't bind the properties to the columns.
ArrayList boxesarray = new ArrayList();
You could create a simple class like this:
public class PropertyContainer
{
public string Value {get;set;}
}
// NOTE: you can override ToString(); to customize String.Format behaviour
// and to show it in the debugger (althought there's other way for this, using
// DebuggerDisplayAttribute)
And create and populate an array of this class, which will be correctly bound to the datagrid.
foreach (PSObject ps in commandResults)
boxesarray.Add(
new PropertyContainer { Value = ps.Properties["Name"].Value.ToString()});
boxes.DataSource = boxesarray;
boxes.DataBind();
Other option is to convert your array to an array of objects using LINQ. You can even use anonymous object if the data grid columns are set to be automatically created.
// anonymous type
var dataForBinding = boxesArray.select(val => new {Value = val});
// array of the class
var dataForBinding = boxesArray.select(val => new PropertyContainer
{ Value = val });
You can bind this data to your gridview, and it will work perfectly.
You can try
.DataSource = (from ps in commandResults
select { Name:ps.Properties["Name"].Value.ToString() }).ToList();
Or
.DataSource = (from name in yourarraylist
select { Name:name.ToString() }).ToList();

Binding Listbox to List<object> in WinForms

What's the simplest way to bind a Listbox to a List of objects in Windows Forms?
You're looking for the DataSource property:
List<SomeType> someList = ...;
myListBox.DataSource = someList;
You should also set the DisplayMember property to the name of a property in the object that you want the listbox to display. If you don't, it will call ToString().
Binding a System.Windows.Forms.Listbox Control to a list of objects (here of type dynamic)
List<dynamic> dynList = new List<dynamic>() {
new {Id = 1, Name = "Elevator", Company="Vertical Pop" },
new {Id = 2, Name = "Stairs", Company="Fitness" }
};
listBox.DataSource = dynList;
listBox.DisplayMember = "Name";
listBox.ValueMember = "Id";
Pretending you are displaying a list of customer objects with "customerName" and "customerId" properties:
listBox.DataSource = customerListObject;
listBox.DataTextField = "customerName";
listBox.DataValueField = "customerId";
listBox.DataBind();
Edit: I know this works in asp.net - if you are doing a winforms app, it should be pretty similar (I hope...)
Granted, this isn't going to provide you anything truly meaningful unless the objects have properly overriden ToString() (or you're not really working with a generic list of objects and can bind to specific fields):
List<object> objList = new List<object>();
// Fill the list
someListBox.DataSource = objList;
ListBox1.DataSource = CreateDataSource();
ListBox1.DataTextField = "FieldProperty";
ListBox1.DataValueField = "ValueProperty";
Please refer to this article for detailed examples.
I haven 't seen it here so i post it because for me is the best way in winforms:
List<object> objList = new List<object>();
listBox.DataSource = objList ;
listBox.Refresh();
listBox.Update();
There are two main routes here:
1: listBox1.DataSource = yourList;
Do any manipulation (Add/Delete) to yourList and Rebind.
Set DisplayMember and ValueMember to control what is shown.
2: listBox1.Items.AddRange(yourList.ToArray());
(or use a for-loop to do Items.Add(...))
You can control Display by overloading ToString() of the list objects or by implementing the listBox1.Format event.
For a UWP app:
XAML
<ListBox x:Name="List" DisplayMemberPath="Source" ItemsSource="{x:Bind Results}"/>
C#
public ObservableCollection<Type> Results

Categories