winform - setting Selected value of listbox - c#

I had a list box called listbox1 will bounded to list like this:
ValueVM word1 = new ValueVM { Id = 1, Name = "AAA" };
ValueVM word2 = new ValueVM { Id = 2, Name = "XBB" };
ValueVM word3 = new ValueVM { Id = 3, Name = "ACC" };
ValueVM word4 = new ValueVM { Id = 4, Name = "ACB" };
ValueVM word5 = new ValueVM { Id = 5, Name = "OTD" };
ValueVM word6 = new ValueVM { Id = 6, Name = "FDD" };
var li = new List<ValueVM>() { word1, word2, word3, word4, word5, word6 };
listBox1.DataSource = li.OrderBy(l=>l.Name).ToList();
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Id";
I want to one Item to be seleted in this list box, suppose I want the Id=2;
int myID = 2;
//Idont know what the selected index will be but I need the selected value to be set
// I tried to set listBox1.SelectedValue=myId.ToString();
//but still returning null
listBox1.SelectedValue = myID;
as mentioned in MSDN:
Gets or sets the value of the member property specified by the ValueMember property. (Inherited from ListControl.)
my problem that seleted value get the value from value member but it didn't set the value?
any Ideas?

You're in the right direction only. SelectedValue should do what you need.
listBox1.SelectedValue = 2;//this works for me
Note: You've to set the int here since datasource is int. setting "2" won't work

Try with
listBox1.SetSelected(MyId, true);
Take a look at this

you should change yourcode into someting like this
listBox1.DataSource = li.OrderBy(l=>l.Name).ToArray();
because the datasource does not understand IOrderedEnumerable
Hopethis help

Related

populate combobox with data from enum

I have enum
public enum MyEnum
{
Choice = 1,
Choicee = 2,
Choiceee = 3
}
and I want to dynamically fill list with this enum values
var data = new List<ComboBoxItem>();
where ComboBoxItem has two properties, Id and Name. Id should be enum int value and name should be enum Value like Choice or Choicee, ...
You can use Enum.GetValues for it:
var values = Enum.GetValues(typeof(SearchOption)).Cast<SearchOption>()
.Select(x => new ComboBoxItem() { Id = (int)x, Name = x.ToString() }).ToList();

ComboBox data types supported

Can I set the data type for a Value of a ComboBox?
I'm have a long list of keyCodes I want to use in the RegisterHotKey() function, which takes an uint VK data type.
RegisterHotKey(_hWnd, 1, (uint)fsModifiers.Control, (uint)Keys.Insert);
I set my combobox value as "(uint)Keys.Insert". Then I assign the value to a string variable and try to use the variable cast as (uint) in the RegisterHotKey function but I keep getting data type errors.
Either I'm not casting right or this can't be done?
Thanks...
cboHotkeyModifier.ValueMember = "Value";
cboHotkeyModifier.DisplayMember = "Text";
items = new[] {
new { Value = "", Text = "" },
new { Value = "Shift", Text = "Shift" },
new { Value = "(uint)fsModifiers.Control", Text = "Control" },
new { Value = "Alt", Text = "Alt" }
};
cboHotkey.ValueMember = "Value";
cboHotkey.DisplayMember = "Text";
items = new[] {
new { Value = "D0", Text = "0" },
new { Value = "D1", Text = "1" },
new { Value = "D2", Text = "2" },
new { Value = "D3", Text = "3" },
new { Value = "D4", Text = "4" },
};
cboHotkey.DataSource = items;
keyData = cboHotkey.SelectedItem;
keyModifier = cboHotkeyModifier.SelectedItem;
RegisterHotKey(_hWnd, 1, keyModifer, keyCode);

Select multiple fields group by and sum

I want to do a query with linq (list of objects) and I really don't know how to do it, I can do the group and the sum but can't select rest of the fields.
Example:
ID Value Name Category
1 5 Name1 Category1
1 7 Name1 Category1
2 1 Name2 Category2
3 6 Name3 Category3
3 2 Name3 Category3
I want to group by ID, SUM by Value and return all fields like this.
ID Value Name Category
1 12 Name1 Category1
2 1 Name2 Category2
3 8 Name3 Category3
Updated :
If you're trying to avoid grouping for all the fields, you can group just by Id:
data.GroupBy(d => d.Id)
.Select(
g => new
{
Key = g.Key,
Value = g.Sum(s => s.Value),
Name = g.First().Name,
Category = g.First().Category
});
But this code assumes that for each Id, the same Name and Category apply. If so, you should consider normalizing as #Aron suggests. It would imply keeping Id and Value in one class and moving Name, Category (and whichever other fields would be the same for the same Id) to another class, while also having the Id for reference. The normalization process reduces data redundancy and dependency.
void Main()
{
//Me being lazy in init
var foos = new []
{
new Foo { Id = 1, Value = 5},
new Foo { Id = 1, Value = 7},
new Foo { Id = 2, Value = 1},
new Foo { Id = 3, Value = 6},
new Foo { Id = 3, Value = 2},
};
foreach(var x in foos)
{
x.Name = "Name" + x.Id;
x.Category = "Category" + x.Id;
}
//end init.
var result = from x in foos
group x.Value by new { x.Id, x.Name, x.Category}
into g
select new { g.Key.Id, g.Key.Name, g.Key.Category, Value = g.Sum()};
Console.WriteLine(result);
}
// Define other methods and classes here
public class Foo
{
public int Id {get;set;}
public int Value {get;set;}
public string Name {get;set;}
public string Category {get;set;}
}
If your class is really long and you don't want to copy all the stuff, you can try something like this:
l.GroupBy(x => x.id).
Select(x => {
var ret = x.First();
ret.value = x.Sum(xt => xt.value);
return ret;
}).ToList();
With great power great responsibility comes. You need to be careful. Line ret.value = x.Sum(xt => xt.value) will change your original collection, as you are passing reference, not new object. If you want to avoid it, you need to add some Clone method into your class like MemberwiseClone (but again, this will create shallow copy, so be careful). Afer that just replace the line with: var ret = x.First().Clone();
try this:
var objList = new List<SampleObject>();
objList.Add(new SampleObject() { ID = 1, Value = 5, Name = "Name1", Category = "Catergory1"});
objList.Add(new SampleObject() { ID = 1, Value = 7, Name = "Name1", Category = "Catergory1"});
objList.Add(new SampleObject() { ID = 2, Value = 1, Name = "Name2", Category = "Catergory2"});
objList.Add(new SampleObject() { ID = 3, Value = 6, Name = "Name3", Category = "Catergory3"});
objList.Add(new SampleObject() { ID = 3, Value = 2, Name = "Name3", Category = "Catergory3"});
var newList = from val in objList
group val by new { val.ID, val.Name, val.Category } into grouped
select new SampleObject() { ID = grouped.ID, Value = grouped.Sum(), Name = grouped.Name, Category = grouped.Category };
to check with LINQPad:
newList.Dump();

C# Linq List Compare and update lists

I have 2 lists containing different types. One is a string[] and another is a List<SelectListItem>.
SelectListItem (it's in mvc):
public string Text {get;set;}
public string Value {get;set;}
public bool Selected {get;set;}
My string[] is just contains some text values.
What i'm trying to do is, get whatever is in the string[], then set "Selected = true" for whatever Value matches, and "Selected = false" for what doesnt match.
So lets say my string[] is:
Test1
Test2
Test3
And my List<SelectListItem> is:
new SelectListItem { Text = "Testing", Value = "Test1", Selected = false },
new SelectListItem { Text = "Testing", Value = "Test4", Selected = true }
In the above List<SelectListItem>, i have one match. So what i'd like to do, is set Selected = true for that particular entry so that i end up with:
new SelectListItem { Text = "Testing", Value = "Test1", Selected = true },
new SelectListItem { Text = "Testing", Value = "Test4", Selected = false }
How would I achieve this?
foreach(var i in selectListItemList)
i.Selected = stringArray.Contains(i.Value);
or using List.ForEach:
selectListItemList.ForEach(i => i.Selected = stringArray.Contains(i.Value));
How about
list.ForEach(x => x.Selected = stringarray.Contains(x.Value))
var items = SelectListItems.Where(p=>stringArray.Contains(p));;
foreach(var item in items)
item.Selected=true;

Using LINQ to count value frequency

I have a table
ID|VALUE
VALUE is an integer field with possible values between 0 and 4. How can I query the count of each value?
Ideally the result should be an array with 6 elements, one for the count of each value and the last one is the total number of rows.
This simple program does just that:
class Record
{
public int Id { get; set; }
public int Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Record> records = new List<Record>()
{
new Record() { Id = 1, Value = 0},
new Record() { Id = 2, Value = 1 },
new Record() { Id = 3, Value = 2 },
new Record() { Id = 4, Value = 3 },
new Record() { Id = 5, Value = 4 },
new Record() { Id = 6, Value = 2 },
new Record() { Id = 7, Value = 3 },
new Record() { Id = 8, Value = 1 },
new Record() { Id = 9, Value = 0 },
new Record() { Id = 10, Value = 4 }
};
var query = from r in records
group r by r.Value into g
select new {Count = g.Count(), Value = g.Key};
foreach (var v in query)
{
Console.WriteLine("Value = {0}, Count = {1}", v.Value, v.Count);
}
}
}
Output:
Value = 0, Count = 2
Value = 1, Count = 2
Value = 2, Count = 2
Value = 3, Count = 2
Value = 4, Count = 2
Slightly modified version to return an Array with only the count of values:
int[] valuesCounted = (from r in records
group r by r.Value
into g
select g.Count()).ToArray();
Adding the rows count in the end:
valuesCounted = valuesCounted.Concat(new[] { records.Count()}).ToArray();
Here is how you would get the number of rows for each value of VALUE, in order:
var counts =
from row in db.Table
group row by row.VALUE into rowsByValue
orderby rowsByValue.Key
select rowsByValue.Count();
To get the total number of rows in the table, you can add all of the counts together. You don't want the original sequence to be iterated twice, though; that would cause the query to be executed twice. Instead, you should make an intermediate list first:
var countsList = counts.ToList();
var countsWithTotal = countsList.Concat(new[] { countsList.Sum() });

Categories