C#: if else statement with listView - c#

what i am trying to do is check if the listView (column5) contains ANY items with the word 'Yes'. If it does write 'Great', if the column does not contain any items at ALL with the word 'Yes' write 'Bad'.
Whats happening now is my program is only writing Bad (the else statement) even if the column does contain an item that has the word 'Yes'.
How can I fix this?:
foreach (ListViewItem item in listView1.Items) {
if (item.SubItems[5].Text.Contains("Yes")) {
// Do your work here
labelContainsVideo2.Text = "GREAT";
labelContainsVideo2.ForeColor = System.Drawing.Color.Green;
} else {
labelContainsVideo2.Text = "BAD";
labelContainsVideo2.ForeColor = System.Drawing.Color.Red;
}
}

Maybe for the case?
foreach (ListViewItem item in listView1.Items)
{
if (item.SubItems[5].Text.ToUpper().Contains("YES"))
{
// Do your work here
labelContainsVideo2.Text = "GREAT";
labelContainsVideo2.ForeColor = System.Drawing.Color.Green;
}
else
{
labelContainsVideo2.Text = "BAD";
labelContainsVideo2.ForeColor = System.Drawing.Color.Red;
}
}
Also, have in mind that this way it will only count the last item. If you want to show all items state you should have a labels array or something. If what you want is to know if any items contains 'Yes', you should follow #ZombieSheep answer.

If the last item in your list doesn't contain "Yes", then the output will be "BAD", regardless of what the other items contain.
Try this instead...
string message = "BAD";
var msgColor = System.Drawing.Color.Red;
foreach (ListViewItem item in listView1.Items)
{
if (item.SubItems[5].Text.Contains("Yes"))
{
message = "GREAT";
msgColor = System.Drawing.Color.Green;
break; // no need to check any more items - we have a match!
}
}
labelContainsVideo2.Text = message ;
labelContainsVideo2.ForeColor = msgColor;

Try this:
if(listView1.Items.Cast<ListViewItem>().Any(i => i.SubItems[5].Text.ToLower().Contains("yes"))){
labelContainsVideo2.Text = "GREAT";
labelContainsVideo2.ForeColor = System.Drawing.Color.Green;
}
else
{
labelContainsVideo2.Text = "BAD";
labelContainsVideo2.ForeColor = System.Drawing.Color.Red;
}

Related

Check if the selected dataGridView row is bold

I have a piece of that requires to change to regular font and remove from a tracker. I need it check if the row is bold but its failing.
private void clientDataGridView_SelectionChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in clientDataGridView.SelectedRows)
{
if (row.DefaultCellStyle.Font.Style == FontStyle.Bold)
{
row.DefaultCellStyle.Font = new Font(DefaultFont, FontStyle.Regular);
new_tracker --;
}
idtxt.Text = row.Cells[0].Value.ToString();
emailtxt.Text = row.Cells[1].Value.ToString();
nametxt.Text = row.Cells[2].Value.ToString();
packagetxt.Text = row.Cells[3].Value.ToString();
notificationToolStripStatusLabel.Text = "0 new notifications";
}
}
I think you need a few extra checks:
if (row == null) result = "row is null";
else if (!row.HasDefaultCellStyle) result = "no row style"; // this helps!
else if (row.DefaultCellStyle.Font == null) result = "no font"; // may work without
else if (row.DefaultCellStyle.Font.Bold) result = "bold";
I found this to work for rows, where I had actually set the HasDefaultCellStyle.

Display records by row number using SqlDataReader

The following code will show the last record in the textboxes. I want to be able to choose which row data to display
while (reader.Read())
{
ListViewItem item = new ListViewItem(reader["item_ID"].ToString());
Item.SubItems.Add(reader["item_Desc"].ToString());
listView1.Items.Add(item);
if(action == "add")
{
txtitemid.Text = "";
txtitem.Text = "";
}
else
{
//this is the part i am taking about
txtitemid.Text = reader.GetValue(0).ToString();
txtitemdesc.Text = reader.GetValue(1).ToString();
}
}
Suppose the last record in the table has an item_ID of 15 and item_Desc is dress then the textboxes will show the following according to code above
txtitemid.Text = 15;
txtitemdesc.Text = "dress";
I want to be able to determine which Item_ID details get displayed in the textboxes
Assign the text box values after your while loop:
if (listView1.Items.Count > 0)
{
var displayedItem = listView1.Items[listView1.Items.Count - 1];
txtitemid.Text = displayedItem.SubItems[0].Text;
txtitemdesc.Text = displayedItem.SubItems[1].Text;
}
else
{
txtitemid.Text = "";
txtitemdesc.Text = "";
}
EDIT:
Similarly, you could display the first item by changing the line in the code above to:
var displayedItem = listView1.Items[0];
if (reader.Read())
{
var readMore = true;
while (readMore)
{
var val = reader.GetValue(0).ToString();
readMore = reader.Read();
if (!readMore)
{
//Last record. Use val .
txtitemid.Text = val;
}
else
{
//Not last record. Process val differently.
}
}
}

Duplicate Entry in listview

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;
}

Search item in list view c#

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
}
}
};

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

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;
}
}
}
}

Categories

Resources