Uhmm... Excuse me can anybody help... I'm trying to compare if item already existing in listview, but first when I add an item it's okay. But when I change the item then add the item it still says duplicate entry. What I want to do is when every time I add an item it will detect if item is already in listview. Thanks in advance!!
while (myReadersup1.Read())
{
string item = myReadersup1.GetString("ProdName");
string price = myReadersup1.GetFloat("ProdPrice").ToString("n2");
string noi = cmbNOI.SelectedItem.ToString();
bool alreadyInList = false;
foreach (ListViewItem itm in lvCart.Items)
{
if (lvCart.Items.Cast<object>().Contains(itm))
{
alreadyInList = true;
MessageBox.Show("Duplicate Entry!");
break;
}
}
if (!alreadyInList)
{
lvCart.Items.Add(new ListViewItem(new string[] { item, price, noi }));
}
In your foreach loop, you need an else that will set alreadyInList to false if the item isn't found. Otherwise, it's always true.
As you foreach through the current items, you are checking to see if it is in the items collection, and that will always be true. You may want to change it to something similar:
private bool AddListViewItem(string item, string price, string noi)
{
if (this.DetectDuplicate(item, price, noi))
return false;
string[] content = new string[] { item, price, noi };
ListViewItem newItem = new ListViewItem();
newItem.Content = content;
_listView.Items.Add(newItem);
return true;
}
private bool DetectDuplicate(string item, string price, string noi)
{
foreach (ListViewItem lvwItem in _listView.Items)
{
string[] itemContent = lvwItem.Content as string[];
Debug.Assert(itemContent != null);
if (itemContent[0].Equals(item) &&
itemContent[1].Equals(price) &&
itemContent[2].Equals(noi))
return true;
}
return false;
}
Related
I got a problem with wpf ComboBox.
I first added a Textbox as the first item to use it for my filtering propose
I then added about 20 Checkboxes in the Combobox through a Foreach loop.
like this
now when i filter them out (i check if true then Visibility.Collapsed) their trace are still in the Combobox like this
Remember that the items are one by one added to the combobox
like this
DataTable machinesTable = machineModel.GetAllMachines().Tables[0];
List<CheckBox> list = new List<CheckBox>();
foreach (DataRow item in machinesTable.Rows)
{
string ID = item["ID"].ToString();
string manufacture = item["MANUFACTURER"].ToString();
string model = item["MODEL"].ToString();
MachinesComboBox.Items.Add(new CheckBox() { Uid = ID, Content = manufacture + " - " + model });
}
and the filtering system works like this
foreach (object item in MachinesComboBox.Items)
{
if (item is CheckBox)
{
if (((CheckBox)item).Content.ToString().Contains(MachinFilterTextbox.Text) || MachinFilterTextbox.Text=="")
{
((CheckBox)item).Visibility = Visibility.Visible;
}
else
{
((CheckBox)item).Visibility = Visibility.Collapsed;
}
}
}
You should look into the MVVM design pattern but as a quick fix you could set the Visibility of the parent ComboBoxItem container:
foreach (CheckBox item in MachinesComboBox.Items.OfType<CheckBox>())
{
ComboBoxItem container = MachinesComboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
if (item.Content.ToString().Contains(MachinFilterTextbox.Text) || MachinFilterTextbox.Text == "")
{
container.Visibility = Visibility.Visible;
}
else
{
container.Visibility = Visibility.Collapsed;
}
}
I try to add item in list view .
But this code like not working at all.
Where did i do wrong ?
btn.Click += (senders, eventArgs) =>
{
foreach (ListViewItem lvis in lvSales.Items)
{
if (lvis.SubItems[0].Text == btn.Text)
{
MessageBox.Show("!!!!!!!");
}
else
{
lvis.Text = count.ToString();
lvis.SubItems.Add(btn.Text);
lvis.SubItems.Add(btn.Name);
lvis.SubItems.Add(count.ToString());
lvis.SubItems.Add(btn.Tag.ToString()); // Email
lvSales.Items.Add(lvis);
count++;
}
}
};
I wan add item to list view.
If the item already added it will add the quantity
else it will add new .
btw when I clicked the button nothing happen .
you cannot add items to the collection you are iterating through with foreach (lvSales.Items). Consider changing foreach to some other loop like 'for(...'
Try this. It is not completely correct but try and fix minor bugs.
var itemFound = false;
foreach (var listViewItem in lvSales.Items)
{
if (listViewItem.SubItems[0].Text == btn.Text)
{
itemFound = true; break;
}
}
if (!itemFound)
{
var newlistViewItem = new ListViewItem();
newlistViewItem.Text = count.ToString();
newlistViewItem.SubItems.Add(btn.Text);
newlistViewItem.SubItems.Add(btn.Name);
newlistViewItem.SubItems.Add(count.ToString());
newlistViewItem.SubItems.Add(btn.Tag.ToString()); // Email
lvSales.Items.Add(lvis);
}
btn.Click += (senders, eventArgs) =>
{
foreach (ListViewItem lvis in lvSales.Items)
{
if (lvis.SubItems[0].Text == btn.Text)
{
//get current quantity of listitem, increment it,
//add the new value to this listitem quantity value...
//keep track of current index, use that to set the new value...
}
else
{
//re instantiate listviewitem, set its values, and add it
}
}
};
So I've been looking to set a default value for my combobox. I found a few things but none of them seem to work.
Actually, it works if I create a simple combobox and use comboBox1.SelectedIndex = comboBox1.Items.IndexOf("something") but once I dynamically generate the contents of the comboboxes, I can't get it to work anymore.
This is how I fill my combo box (located in the class's constructor);
string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
List<string[]> list = database.Select(command, false);
cbxCategory.Items.Clear();
foreach (string[] result in list)
{
cbxCategory.Items.Add(new ComboBoxItem(result[1], result[0]));
}
I can't seem to get it to work to set a default value, like if I place cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New") below the above code, it won't work.
WinForms, by the way.
Thank you in advance.
cbxCategory.SelectedIndex should be set to an integer from 0 to Items.Count-1 like
cbxCategory.SelectedIndex = 2;
your
cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New")
should return -1 as long as no ComboboxItem mutches the string ("New");
another solution though i don't like it much would be
foreach(object obj in cbxCategory.Items){
String[2] objArray = (String[])obj ;
if(objArray[1] == "New"){
cbxCategory.SelectedItem = obj;
break;
}
}
perhaps this also requires the following transformation to your code
foreach (string[] result in list)
{
cbxCategory.Items.Add(result);
}
I haven't tested the code and i am not sure about the casting to String[2] but something similar should work
It looks like you're searching the cbxCategory.Items collection for a string, but it contains items of type ComboBoxItem. Therefore the search will return -1.
You can use LINQ.
//string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
//List<string[]> list = database.Select(command, false);
// sample data...
List<string[]> list = new List<string[]> { new string[] { "aaa", "bbb" }, new string[] { "ccc", "ddd" } };
cbxCategory.Items.Clear();
foreach (string[] result in list)
{
cbxCategory.Items.Add(new ComboBoxItem(result[1], result[0]));
}
ComboBoxItem tmp = cbxCategory.Items.OfType<ComboBoxItem>().Where(x => x.ResultFirst == "bbb").FirstOrDefault();
if (tmp != null)
cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf(tmp);
ComboBoxItem class:
class ComboBoxItem
{
public string ResultFirst { get; set; }
public string ResultSecond { get; set; }
public ComboBoxItem(string first, string second)
{
ResultFirst = first;
ResultSecond = second;
}
}
Here's my simple solution
var list = comboBox1.Items.Cast<string>().ToList();
cbxCategory.SelectedIndex = list.FindIndex(c => c.StartsWith("test"));
My solution:
int? defaultID = null;
foreach (DataRow dr in dataSource.Tables["DataTableName"].Rows)
{
if ((dr["Name"] != DBNull.Value) && ((string)dr["Name"] == "Default Name"))
{
defaultID = (int)dr["ID"];
}
}
if (defaultID != null) comboBox.SelectedValue = defaultID;
I am creating a CheckBoxList in a class file and am using an HTMLTextWriter to render the control.
I'm using the following code to store the selected values in a string:
string YrStr = "";
for (int i = 0; i < YrChkBox.Items.Count; i++)
{
if (YrChkBox.Items[i].Selected)
{
YrStr += YrChkBox.Items[i].Value + ";";
}
}
I stepped through the code and it doesn't seem to hit the inside of the if statement & the selected value attribute is false every time ... Anyone have an idea of how I can address this?
I populate it using the following:
YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
In your ASPX page you've got the list like this:
<asp:CheckBoxList ID="YrChkBox" runat="server"
onselectedindexchanged="YrChkBox_SelectedIndexChanged"></asp:CheckBoxList>
<asp:Button ID="button" runat="server" Text="Submit" />
In your code behind aspx.cs page, you have this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Populate the CheckBoxList items only when it's not a postback.
YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
YrChkBox.Items.Add(new ListItem("Item 2", "Item2"));
}
}
protected void YrChkBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Create the list to store.
List<String> YrStrList = new List<string>();
// Loop through each item.
foreach (ListItem item in YrChkBox.Items)
{
if (item.Selected)
{
// If the item is selected, add the value to the list.
YrStrList.Add(item.Value);
}
else
{
// Item is not selected, do something else.
}
}
// Join the string together using the ; delimiter.
String YrStr = String.Join(";", YrStrList.ToArray());
// Write to the page the value.
Response.Write(String.Concat("Selected Items: ", YrStr));
}
Ensure you use the if (!IsPostBack) { } condition because if you load it every page refresh, it's actually destroying the data.
Try something like this:
foreach (ListItem listItem in YrChkBox.Items)
{
if (listItem.Selected)
{
//do some work
}
else
{
//do something else
}
}
check boxlist selected values with seperator
string items = string.Empty;
foreach (ListItem i in CheckBoxList1.Items)
{
if (i.Selected == true)
{
items += i.Text + ",";
}
}
Response.Write("selected items"+ items);
An elegant way to implement this would be to make an extension method, like this:
public static class Extensions
{
public static List<string> GetSelectedItems(this CheckBoxList cbl)
{
var result = new List<string>();
foreach (ListItem item in cbl.Items)
if (item.Selected)
result.Add(item.Value);
return result;
}
}
I can then use something like this to compose a string will all values separated by ';':
string.Join(";", cbl.GetSelectedItems());
// Page.aspx //
// To count checklist item
int a = ChkMonth.Items.Count;
int count = 0;
for (var i = 0; i < a; i++)
{
if (ChkMonth.Items[i].Selected == true)
{
count++;
}
}
// Page.aspx.cs //
// To access checkbox list item's value //
string YrStrList = "";
foreach (ListItem listItem in ChkMonth.Items)
{
if (listItem.Selected)
{
YrStrList = YrStrList + "'" + listItem.Value + "'" + ",";
}
}
sMonthStr = YrStrList.ToString();
// aspx.cs
// Load CheckBoxList selected items into ListBox
int status = 1;
foreach (ListItem s in chklstStates.Items )
{
if (s.Selected == true)
{
if (ListBox1.Items.Count == 0)
{
ListBox1.Items.Add(s.Text);
}
else
{
foreach (ListItem list in ListBox1.Items)
{
if (list.Text == s.Text)
{
status = status * 0;
}
else
{
status = status * 1;
}
}
if (status == 0)
{ }
else
{
ListBox1.Items.Add(s.Text);
}
status = 1;
}
}
}
}
Can anyone help me to solve my little trouble?
I'm writing an app to work with text files. And I have GUI which contains a listView with checkboxes for each item.
I've created 2 arrays:
1st for items in listView and 2nd for all lines in a text file
string[] itemInList = new string[] { listView1.Items.ToString()
string[] lineInHosts = File.ReadAllLines(C:\Test.txt).ToArray<string>();
The idea is to compare all lines in "C:\Test.txt" file and all items in the listView.
If there will be a match, I want this item to be item.Checked = true;
PS: I've tried this -
foreach (var item in itemInList)
{
foreach (var l in lineInHosts)
{
string itemName;
ListViewItem foundItem;
if (item == l)
{
itemName = item.ToString();
foundItem = listView1.FindItemWithText(itemName);
foundItem.Checked = true;
}
}
}
but it doesn't work.
First line should be different and the second loop is not efficient:
string[] itemInList = listView1.Items.OfType<ListViewItem>( ).Select( p => p.Text ).ToArray( );
string[] lineInHosts = File.ReadAllLines( #"C:\Test.txt" ).ToArray<string>( );
string itemName;
ListViewItem foundItem;
foreach ( var item in itemInList )
{
if (lineInHosts.Contains(item))
{
itemName = item.ToString( );
foundItem = listView1.FindItemWithText( itemName );
foundItem.Checked = true;
}
}
This line looks suspicious :)
string[] itemInList = new string[] { listView1.Items.ToString()
There will be only one item in itemInList, and it will be called like your type.
Instead use:
string[] itemInList = listView1.Items.Select(x => x.ToString()).ToArray();
Try below answer, hope it will save someone's time
foreach (var room in customerRooms)
{
lstViewRooms.Items.Cast<ListViewItem>().Where(x =>.Text.Contains(room.Room.ToString())).FirstOrDefault().Selected = true;
}