Switch Case for dynamic amount of values - c#

So this is my Program
You can add as much rows as you want to this gridview and when you press the 'Ready' button the program watches your input via the KeyDown-Event.
When you press one of those Hotkeys shown in the gridview you get all the songs which are in the matching path.
I thought I could do something like this:
switch (e.KeyValue.ToString().Substring(0, 0))
{
foreach (DataGridViewRow item in grdView)
{
case item.Cells[2].Value:
//Get all the songs
break;
}
}
Unfortunatelly I get tons of errors. I guess it won't work like this.
Is there any other way to ask for all Hotkeys written in the gridview?
Thanks for any kind of advice.

foreach (DataGridViewRow item in grdView)
{
if(item.Cells[2].Value == theValueYouAreLookingFor)
{
// Do something here
break;
}
}
And also e.KeyValue.ToString().Substring(0, 0) doesn't look right, I'm pretty sure that it isn't going to do quite what you want it to do.

Although iterating through all items with foreach and checking for equals would work,
I thought its worth to mention few alternative in case someone finds it in the future:
one is Linq:
var itemFound = grdView.FirstOrDefault(item => item.Cells[2].Value == theValueYouAreLookingFor);
if (itemFound == null)
{
//no items found in this case
}
the other is Dictionary which is a more efficient solution to map dynamic amount of options in general, but it you'll have to build it beforehand:
simple build example (do this when the grid is created/changed):
shortcutsMap = grdView.ToDictionary(item => item.Cells[2].Value, item);
get:
var itemFound = shortcutsMap[theValueYouAreLookingFor] //will throw exception if not found
or:
shortcutsMap.TryGetValue(theValueYouAreLookingFor, out var itemFound) //returns true/false if found and result will be at itemFound

Related

C# Search item and return in Listview

I have some question about Listview in C#
My listview contains with 2 column like this :
colDATA1 colDATA2
Value1 Amount1
Value2 Amount2
Value3 Amount3
Value4 Amount4
And what I am trying to make is search Amount5 in Listview If not exist then do something.And if exist then return the Value5
I am trying to search and use the code like this :
If (Listview1.items.containskey("Amount5"))
{}
else
{MessageBox.show("Not Found")}
or if exist then return the value5 *I have no idea how to do.
I am searching this in google but most of it have only 1 Column and when I use the code the code won't work.
My question is :
1. How can I get Value5 if Amount5 exist.
Thank you.
The code to add the items
First Set listView1 Property "View : Details" Then Using this code
this.Listview1.Items.Add(new ListViewItem(new string[] { Value1, Amount1 }));
The OP already figured it out but this is just for future reference in case someone needs it.
What OP was missing is that ListView holds its items as objects in the Items property.
If (Listview1.items.containskey("Amount5"))
{}
else
{MessageBox.show("Not Found")}
containsKey is usually in dictionaries-like data structures. However, a ListView controller's Items is ItemCollection (for dictionaries you can use a DataGrid)
In your case I would do this using Linq.
// Returns the first item that satisfies the condition or null if none does.
ListViewItem found = items.FirstOrDefault(i => i.SubItems[1].Text.Equals("Amount5"));
if(found != null) {
MessageBox.Show(found.SubItems[0].Text.ToString());
}
else {
MessageBox.Show("Not Found!");
}
You can still use a for loop to do the same thing too.
If I want to use a foreach loop (since Linq can't be directly used on ListView.Item)
ListViewItem found = null;
foreach (ListViewItem item in listView1.Items) {
if (item.SubItems[1].Text.Equals("Amount5")) {
// If a match was found break the loop.
found = item;
break;
}
}
if (found != null) {
MessageBox.Show(found.SubItems[0].Text.ToString());
}
else {
MessageBox.Show("Not Found!");
}
Hope this helps!

c# Collapse Fields in Excel PivotTable

I have a pre-made Excel with PivotTable that gets Data from another worksheet, I fill via c# code.
In the PivotTable there are three Row fields, which after getting populated and the Pivot refreshed via code, make all the rows expanded after opening the Excel.
I already tried using the DrilledDown method (in the fields, but I get an error), the ShowDetails only works in the items (inside the fields).
I got it to work, but it takes too much time because it uses the ShowDetails in each item, is there any other way, and quick for collapsing the fields? (opening the Excel and doing it manually is not an option).
My Code (which collapses the fields are):
listItems.Add("Data");
listItems.Add("Months");
listItems.Add("Grocery");
Microsoft.Office.Interop.Excel.PivotFields pfs = (Microsoft.Office.Interop.Excel.PivotFields)pivot.PivotFields();
foreach (String s in listItems)
{
Microsoft.Office.Interop.Excel.PivotField pf = (Microsoft.Office.Interop.Excel.PivotField)pivot.PivotFields(s);
foreach (Microsoft.Office.Interop.Excel.PivotItem item in (Microsoft.Office.Interop.Excel.PivotItems)pf.PivotItems())
{
if (item.Value == "(blank)")
item.Visible = false;
item.ShowDetail = false;
}
}
The thing is, maybe there's an easy and quicker way? I was trying something like
pf.DrilledDown = False;
or
pf.ShowDetail = False;
But it doesn't work. Any Ideas?
Well, manage from somehow to only collapse the first item in each field (that way the cycle doesn't go until the end, and since Excel collapses automatically the other similar items (when you collapse one of the same type field), it works).
PS: Since the first field from the groceries is allways the "_blank" one, i know for sure there's allways something after the "_blank" one, but I cannot apply only the collapse to the "_blank", because then it doesn't apply to the other items (I supposed it must be something with a Value inside).
So...got this (it's a lot more quick, but still, I think it shall exist another way (with simpler code in c# (without using VB macros inside the Excel)), but if there is, it's hard to find - few people manipulate pivot tables programatically.
listItems.Add("Date");
listItems.Add("Months");
listItems.Add("Groceries");
Microsoft.Office.Interop.Excel.PivotFields pfs = (Microsoft.Office.Interop.Excel.PivotFields)pivot.PivotFields();
foreach (String s in listItems)
{
Microsoft.Office.Interop.Excel.PivotField pf = (Microsoft.Office.Interop.Excel.PivotField)pivot.PivotFields(s);
foreach (Microsoft.Office.Interop.Excel.PivotItem item in (Microsoft.Office.Interop.Excel.PivotItems)pf.PivotItems())
{
if (pf.Value == "Date")
{
item.ShowDetail = false;
break;
}
if (pf.Value == "Months")
{
item.ShowDetail = false;
break;
}
if (pf.Value == "Groceries")
{
if (item.Value == "(blank)")
{
item.Visible = false;
continue;
}
item.ShowDetail = false;
break;
}
}
}

Delete rows which has a specific value from DataGridView C#

I have a WinForm DataGridView as follows where I need to delete rows which having a specific value in a column
In this case I'm using a textfield to type Code and after clicking "Delete" all the rows which having ITM-000001 under column value. I have no clue where to start.
private void deleteClick(object sender, EventArgs e)
{
String code = txtCode.Text;
// CODE HERE
}
Not necessarily better or even simpler than Matthew's solution; just a different approach I sometimes find useful:
List<DataGridViewRow> RowsToDelete = new List<DataGridViewRow>();
foreach (DataGridViewRow row in dataGridView1.Rows)
if ( row.Cells[0].Value != null &&
row.Cells[0].Value.ToString() == "TTTT") RowsToDelete.Add(row);
foreach (DataGridViewRow row in RowsToDelete) dataGridView1.Rows.Remove(row);
RowsToDelete.Clear();
This way you could use the list as a buffer after or give the number of hits before actually deleting them.
I also liked his use of string.Equals and do it differently here just for fun..
It's been a long while since I did anything with Windows Forms (oh, the good ol' days), so excuse me if this is a little off, but you should be able to accomplish this with something like...
for(int v = 0; v < dataGrid1.Rows.Count; v++)
{
if(string.Equals(dataGrid1[0, v].Value as string, "ITM-000001"))
{
dataGrid1.Rows.RemoveAt(v);
v--; // this just got messy. But you see my point.
}
}

Selecting multiple Listbox items through code

Hi there I have searched for a while now and can't seem to find a solution to my problem, I have tried multiple methods to select multiple items in my listbox through code however none have worked, The best result I got was 1 selected item in my listbox.
Basically I want to select multiple items of the same value.
below is my code, sorry if I seem newbie but I am new to programming and still learning basic stuff.
foreach (string p in listBox1.Items)
{
if (p == searchstring)
{
index = listBox1.Items.IndexOf(p);
listBox1.SetSelected(index,true);
}
}
So as you can see I am trying to tell the program to loop through all the items in my listbox, and for every item that equals "searchstring" get the index and set it as selected.
However all this code does is select the first item in the list that equals "searchstring" makes it selected and stops, it doesn't iterate through all the "searchstring" items.
As suggested in the comment, you should set SelectionMode to either MulitSimple or MultiExpanded depending on your needs, but you also need to use for or while loop instead offoreach, because foreach loop doesn't allow the collection to be changed during iterations. Therefore, even setting this Property won't make your code run and you will get the exception. Try this:
for(int i = 0; i<listBox1.Items.Count;i++)
{
string p = listBox1.Items[i].ToString();
if (p == searchstring)
{
listBox1.SetSelected(i, true);
}
}
You can set SelectionMode either in the Properties window when using designer or in, for instance, constructor of your Form using this code:
listBox1.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;

Check all item in listview with huge list item?

I want to check about 3000 item in listview. This is a bit of code :
foreach (ListViewItem item in this.lvItem.Items)
{
item.Checked = !item.Checked;
}
But listview is very slow when item is checked. Please give me some ideas to solve this problem? Thanks.
I had the same problem but I found why.
I had an "ItemChecked" event handler attached to my listView that was doing some heavy stuff.
I removed the eventHandler and it solved my problem.
Try removing any "ItemChecked" eventhandler and see if the speed is better.
You need to call BeginUpdate before the loop and EndUpdate after the loop:
listView1.BeginUpdate();
foreach (ListViewItem item in listView1.Items)
item.Checked = true;
listView1.EndUpdate();
Calling BeginUpdate prevents the control from drawing until the EndUpdate method is called.
I heard a rumor that for large list items a for loop will work faster than a foreach loop
try
for(int i = 0; i = < this.1vItem.Items.Count; i++)
{
//Stuff
}
I also don't think it's wise to expect a user to click 3000 items. But something I did recently, when adding the items, knowing that there would never be many and by default they should be checked, is check the items before adding them to the list.
Something like this:
foreach (Recipient recipient in recipients)
{
var item = new ListViewItem(recipient.FirstName + " " + recipient.LastName);
item.Tag = recipient;
item.Checked = true;
lvRicipients.Items.Add(item);
}
Will something like this work for you? ...when checked, add the items to a Dictionary ...when unchecked, remove from the Dictionary. Not tested code but wondering if you could do something like this:
Dictionary<String, ListViewItem> Dic = listView.Items
.Cast<ListViewItem>()
.ToDictionary(x => x.Text, x => x.SubItems[0].Checked);
You asked how to better go about it. What I am saying is on your Check Event you will want to add items to your list view. I doubt that a user will actually check all 3000, so change your code to decide how you would want to handle checked items, the example that I have given you uses Lambda expression. If not familiar, then please alter your question to reflect what it is that you actually need and/or want...
for (int i = 0; i <= listView1.Items.Count - 1; i++)
{
if (!listView1.Items[i].Checked)
listView1.Items[i].Checked = true;
}

Categories

Resources