How to traverse the list view column - c#

How to traverse the list view column so that we can check whether item in the list view column already exist or not and if it exist then change the item .
for example i have a list view with (quantity and item) and i want to check if the newly added item already exist in the list view then only change the quantity to quantity ++ rather then adding new item.
string[] saLvwItem = new string[4];
saLvwItem[0] = a.ToString();
saLvwItem[1] = r["ItemNumber"].ToString();
saLvwItem[2] = r["ItemName"].ToString();
saLvwItem[3] = r["Price"].ToString();
ListViewItem lvi = new ListViewItem(saLvwItem);
listView1.Items.Add(lvi);
all the values are coming from database.

If you are trying to match on ItemName (columnIndex=2) and increase the ItemNumber (columnIndex=1), then this may work:
private void InsertOrUpdateItem(ListView listView, string[] saLvwItem)
{
if (saLvwItem == null || saLvwItem.Length < 4)
{
return;
}
bool bFound = false;
foreach (ListViewItem lvi in listView.Items)
{
if (lvi.SubItems[2].Text == saLvwItem[2])
{
// item already in list
// increase the ItemNumber
lvi.SubItems[1].Text = (Convert.ToInt32(lvi.SubItems[1].Text) + Convert.ToInt32(saLvwItem[1])).ToString();
bFound = true;
break;
}
}
if (!bFound)
{
// item not found
// create new item
ListViewItem newItem = new ListViewItem(saLvwItem);
listView.Items.Add(newItem);
}
}

Use following code,
if(!lvi.ContainsKey(saLvwItem[1]))
{
ListViewItem lvi = new ListViewItem(saLvwItem[2]); //Or whatever value you want to show as name
listView1.Items.Add(lvi);
}
Listview has a key-value setting for every item, so you can't set four properties. Your key should be unique and your name should be exactly what you want to display, you can make a name by concatinating 2 or more values.

Related

How to set Item checked in a checkedlistbox based on Key value?

I have checkedListbox for which i am binding values with Id and Values, when the items are checked i'm saving the Id's in the database, when the form loads i want the checkedListbox items to be checked based on the Id's
I am only able to bind the checkedlistbox based on the index as below , the other alternative i see is getting the Index of the value and checking it but this will not work in my case as i have only the Id's of the checkedlistbox items which needs to be checked.
int index = checkedListBox1.Items.IndexOf("42");
checkedListBox1.SetItemChecked(index , true);
this is how I am binding values
ccBoxitem item = new ccBoxitem(a.name, a.id);
checkedListBox1.items.add(item);
public ccBoxitem (string name, int val)
{
this.name = name;
this.val = val;
}
How can I check the checkedlistbox based on the id's ?
For example, you can loop through your items, then check the one you want:
private void CheckItem(int id)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if ((checkedListBox1.Items[i] as ccBoxitem)?.val == id)
{
checkedListBox1.SetItemChecked(i, true);
}
}
}
usage:
var id = GetId();
CheckItem(id);
You can use below method it will select needed item by its value first then check the selected item
void CheckItem(CheckedListBox checkedListBox, int id)
{
checkedListBox.SelectedItem = checkedListBox.Items.OfType<ccBoxitem>().ToList().FirstOrDefault(i => i.val == id);
checkedListBox.SetItemChecked(checkedListBox.SelectedIndex, true);
checkedListBox.SelectedItem = null; // To clear selection if needed
}
And you can call it as below
CheckItem(checkedListBox1, 3);
CheckItem(checkedListBox1, 6);

How to get multiple selected items in asp.net listbox and show in a textbox?

i am trying to add the selected items from the listbox to the textbox with the comma seperated between each other. but it is only reading the first element of the selected items every time.if i select three values holding ctrl its only passing the fist elemnt of selected items
if (ListBox1.SelectedItem != null)
{
// int count = ListBox1.SelectedItems.Count;
if (TextBox1.Text == "")
TextBox1.Text += ListBox1.SelectedItem.ToString();
else
TextBox1.Text += "," + ListBox1.SelectedItem.ToString();
}
if listbox contain :1,2,3,4
example output inside textbox: 1,1,1,1
expected output: 1,2,3,4 (for evry selection it shouldnt display the already selected value again)
var selectedItemText = new List<string>();
foreach (var li in ListBox1.Items)
{
if (li.Selected == true)
{
selectedItemText.Add(li.Text);
}
}
Then
var result = string.Join(selectedItemText,",");
The ListBox has a SelectedItems property, that you can iterate over:
foreach (var item in ListBox1.SelectedItems)
{
TextBox1.Text += "," + item.ToString();
}
At the end you need to remove the first "," as it will be in front of the first items string representation:
TextBox1.Text = TextBox1.Text.Substring(1, TextBox1.Text.Legth - 1);
Try this
var selected = string.Join(",", yourListBox.Items.GetSelectedItems());
public static class Extensions
{
public static IEnumerable<ListItem> GetSelectedItems(
this ListItemCollection items)
{
return items.OfType<ListItem>().Where(item => item.Selected);
}
}

Adding groups and items to ListView in C# windows form

I'm trying to create a ListView in Windows Form that contains groups and items i get from DataBase.
My ListView is called "lstItems"
In the begining, the ListView is empty and I fill it with data during the runnig of the program.
This is the code I use to create the groups:
foreach(DataRow r in tasksTbl.Rows)
{
string groupName = "group" + num;
num++;
lstItems.Groups.Add(groupName, r.Field<string>(0));
}
The tasksTbl table is not empty and it creates several group that I cannot see on the screen at this point.
This is the code I use to create the items and subItems for the groups:
private void CreateItem(DataTable tbl)
{
int taskId = tbl.Rows[0].Field<int>(0);
string taskName = tbl.Rows[0].Field<string>(1);
DateTime startDate = tbl.Rows[0].Field<DateTime>(2);
DateTime endDate = tbl.Rows[0].Field<DateTime>(3);
string dateStr = startDate.ToString() + " - " + endDate.ToString();
ListViewItem item = new ListViewItem(dateStr);
item.Tag = taskId.ToString();
foreach (DataRow r in tbl.Rows)
{
string position = r.Field<string>(5);
string soldier = r.Field<string>(6);
item.SubItems.Add(soldier + " (" + position + ")");
}
foreach(ListViewGroup grp in lstItems.Groups)
if (grp.Header.Equals(taskName))
grp.Items.Add(item);
}
Here also the tbl table is not empty and it creates the items and sub items to each group.
I can see in the debugger that the groups has the items properly.
My problem is that I cannot see the groups or the items on the screen.
What am I missing?
Can someone give me a hand?
Thank you in advance!
I figured out my problem.
I needed to add columns to the ListView and then, to add the items to the ListView and only in the end to add the items to the groups.
I did it and now it works.
itzick,
You need to create the groups as you go and assign them to the items you add to the ListView Control.
Here is a simple example which loads a ListView with the numbers 65 to 76. The groups are based upon the number modulus 5.
Create a form, add a ListView called listView1, add the method below and call that method during form load. You should see a ListView with five groups and a few member items in each group.
private void LoadListView()
{
// Assume we are in a form, with a ListView control called listView1 on the form
// Create a group label array
var groupLabels = new string[5];
groupLabels[0] = "aaa";
groupLabels[1] = "bbb";
groupLabels[2] = "ccc";
groupLabels[3] = "ddd";
groupLabels[4] = "eee";
for (var i = 65; i < 76; i++)
{
// Find group or create a new group
ListViewGroup lvg = null;
var found = false;
foreach (var grp in listView1.Groups.Cast<ListViewGroup>().Where(grp => grp.ToString() == groupLabels[i % 5]))
{
found = true;
lvg = grp;
break;
}
if (!found)
{
// Group not found, create
lvg = new ListViewGroup(groupLabels[i % 5]);
listView1.Groups.Add(lvg);
}
// Add ListViewItem
listView1.Items.Add(new ListViewItem {Text = i.ToString(CultureInfo.InvariantCulture), Group = lvg});
}

How do i compare a value to a multiple list items in a dropdownlist?

I'm trying to do a logic here where by if an item from db exists in part of the dropdownlist ListItem it will have that item selected, else it will display the new item in a textbox and have the "Others" selected in the dropdownlist.
This is what I have so far
string gameData = readGame["gTitle"].ToString();
string gameTitle = ddlgameTile.Items.ToString();
if (printHouseData == gameTitle)
{
ddlgameTile.SelectedIndex = ddlgameTile.Items.IndexOf(ddlgameTile.Items.FindByValue(gameData));
}
else
{
txtNewGame.Text = readGame["gTitle"].ToString();
ddlgameTile.SelectedIndex = ddlgameTile.Items.IndexOf(ddlgameTile.Items.FindByValue("Others"));
}
I tried using Foreach loop and for loop, it still would not work (properly). It only gets the if-else logic by the last ListItem which is the "Others".
Assuming that gameData is the db item you want to select if it does exist, you can use ListItemCollection.FindByValue to get the item or null if it does not exist. Then you can set DropDownList.SelectedValue to select it:
string selectedValue = "Others";
if(ddlgameTile.Items.FindByValue(gameData) != null)
selectedValue = gameData;
ddlgameTile.SelectedValue = selectedValue;
However, if you have set the DataValueField and DataTextField you have to use FindByText.
How about something like this?
var compareTo = new ListItem("Title","Value");
if (ddl.Items.Contains(compareTo))
{
var selectedIndex = ddl.Items.IndexOf(compareTo);
}
else
{
var selectedIndex =
ddl.Items.IndexOf(new ListItem { Value = "Others", Text = "Others" });
}
Assuming I have the context of what you're trying to achieve right, try this:
foreach (string gameTitle in ddlgameTile.Items)
{
if (printHouseData == gameTitle)
{
ddlgameTile.SelectedIndex = ddlgameTile.Items.IndexOf(ddlgameTile.Items.FindByValue(gameData));
}
else
{
txtNewGame.Text = readGame["gTitle"].ToString();
ddlgameTile.SelectedIndex = ddlgameTile.Items.IndexOf(ddlgameTile.Items.FindByValue("Others"));
}
}

Drag and add items to ListView

I have a ListView with 3 groups.
I drag an item from TreeView to ListView:
private void listViewDemo_DragDrop(object sender, DragEventArgs e)
{
if (!is_listview) //treeview item
{
//get a text of a draged item
string str = e.Data.GetData(DataFormats.Text).ToString();
//get information about hovered item
ListViewHitTestInfo hit_info = listViewDemo.HitTest(listViewDemo.PointToClient(new Point(e.X, e.Y)));
//check position - must be on an item
if (hit_info.Location == ListViewHitTestLocations.None) return;
ListViewItem prev_item = hit_info.Item;
ListViewGroup group = prev_item.Group;
int idx = prev_item.Index;
//create a new key
Guid key = Guid.NewGuid();
string item_key = key.ToString();
//create a new item
//option 1
group.Items.Add(listViewDemo.Items.Insert(idx,item_key, str, ""));
//option2
//group.Items.Insert(idx,listViewDemo.Items.Insert(idx, item_key, str, ""));
}
}
I expect to add an item in place of pointed item, but any option adds element in the end of the group.
How can i add the item in the spot where mouse hover?
Assuming that you want to place the item before the item at the mouse pointer...(this is a bit brute force, but it works).
I also want to note that your original code was finding the index of the hotspot item in the entire list. I added the IndexOf call to get it from the group.
if (!is_listview) //treeview item
{
//get a text of a dragged item
string str = e.Data.GetData(DataFormats.Text).ToString();
//get information about hovered item
ListViewHitTestInfo hit_info = listView1.HitTest(listView1.PointToClient(new Point(e.X, e.Y)));
//check position - must be on an item
if (hit_info.Location == ListViewHitTestLocations.None) return;
ListViewItem prev_item = hit_info.Item;
ListViewGroup group = prev_item.Group;
int idx = group.Items.IndexOf(prev_item);
//create a new key
Guid key = Guid.NewGuid();
string item_key = key.ToString();
//create a new item
//option 1
List<ListViewItem> list = new List<ListViewItem>();
while(group.Items.Count > 0)
{
ListViewItem lvi = group.Items[0];
listView1.Items.Remove(lvi);
list.Add(lvi);
}
group.Items.Clear();
ListViewItem item = new ListViewItem(str, "");
item.Name = item_key;
list.Insert(idx, item);
foreach (ListViewItem i in list)
{
listView1.Items.Add(i);
group.Items.Add(i);
}
}

Categories