Refresh a listbox to display new values - c#

This is a newb question so I'm sorry.
I'm filling out my text box with values Im grabbing on line and passing them to the listbox like so:
// textBox1.Text = test.ToString();
string[] names = result.Split('|');
foreach (string name in names)
{
listBox1.Items.Add(name);
}
However I'm trying to click on a folder and have the files displayed from there be shown in my listbox1. THis is what I've tried:
using (var testy = new WebClient())
{
test = testy.DownloadString("http://server.foo.com/images/getDirectoryList.php?dir=test_folder");
string[] names1 = test.Split('|');
foreach (string name in names1)
{
listBox1.Items.Clear();
listBox1.Items.Add(name);
listBox1.Update();
}
}
But all that happens is that my listbox empties and doesn't get refreshed. How can I achieve what I want to do?

before you do anything else remove the clear and update from the foreach
listBox1.Items.Clear();
foreach (string name in names1)
{
listBox1.Items.Add(name);
}
listBox1.Update();

your lines
foreach (string name in names1)
{
listBox1.Items.Clear();
listBox1.Items.Add(name);
listBox1.Update();
}
makes it that for every string you are removing ever other item in the list.
i'm pretty sure that's not what you want

Use a BindingSource
BindingSource bs = new BindingSource();
List<string> names1 = new List();
bs.DataSource = names1;
comboBox.DataSource = bs;
using (var testy = new WebClient())
{
test = testy.DownloadString("http://server.foo.com/images/getDirectoryList.php?dir=test_folder");
names1.AddRange(test.Split('|'));
bs.ResetBindings(false);
}
The BindingSource will take care of everything for you.

Related

Check if item is found in text file

How can I check if a text file contains an item from a listbox. To stop saving duplicates. I'm not sure what I'd add to this. This is called on a button click event. For example, if a duplicate was found, I could show MessageBox.Show ("duplicate error");
using (StreamWriter writer = new StreamWriter("test.txt", true))
{
foreach (object item in listBox2.Items)
{
writer.WriteLine(item.ToString());
}
}
Before writing to "test.txt", enumerate its contents:
var fileLines = File.ReadAllLines("test.txt");
List<string> fileItems = new List<string>(fileLines);
Then before you write each item, check to see if the list contains it:
using (StreamWriter writer = new StreamWriter("test.txt", true))
{
foreach (object item in listBox2.Items)
{
if (fileItems.Contains(item))
// Do something, break, etc.
else
writer.WriteLine(item.ToString());
}
}
Edit:
Per suggestions, you can use a HashSet instead of a List for performance, as it can only contain unique values.
Another improvement may be to check if any duplicates exist before writing anything to the file. I've done that in the example below in a LINQ statement:
var fileLines = File.ReadAllLines("test.txt");
HashSet<string> fileItems = new HashSet<string>(fileLines);
using (StreamWriter writer = new StreamWriter("test.txt", true))
{
bool duplicateFound = fileItems.Any(fi => listBox1.Items.Cast<string>().Any(i => i == fi));
if (duplicateFound)
MessageBox.Show("Duplicate items found.");
else
foreach (object item in listBox1.Items)
writer.WriteLine(item.ToString());
}
Edit 2:
As #Servy suggested, the listbox could contain duplicates, which should also be taken into consideration. Additionally, my HashSet implementation was sub-par. So in this third example, I am first checking if the listbox contains duplicates, then if any of the listbox items are already in the file. The usage of HashSet is more performant as well because I am not iterating it.
var fileLines = File.ReadAllLines("test.txt");
HashSet<string> fileItems = new HashSet<string>(fileLines);
List<string> duplicateListboxItems = listBox1.Items.Cast<string>().GroupBy(l => l).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
if (duplicateListboxItems.Count > 0)
{
MessageBox.Show("The listbox contains duplicate entries.");
return;
}
bool duplicateFound = false;
List<string> outputItems = new List<string>();
foreach (string item in listBox1.Items)
{
if (fileItems.Contains(item))
{
MessageBox.Show(String.Format("The file has a duplicate: {0}", item));
duplicateFound = true;
break;
}
outputItems.Add(item);
}
if (duplicateFound)
return;
using (StreamWriter writer = new StreamWriter("test.txt", true))
{
foreach (string s in outputItems)
writer.WriteLine(s);
}
string filePath = "test.txt";
var existingLines = new HashSet<string>(File.ReadAllLines(filePath));
var linesToWrite = new List<string>();
foreach (string item in listBox2.Items)
{
if (existingLines.Add(item))
{
linesToWrite.Add(item);
}
else
{
//this is a duplicate!!!
}
}
File.AppendAllLines(filePath, linesToWrite);

Looping through a Listbox created on the fly

I am working on exporting data and right now some fields export the value, instead of the text. So I am saving the object that returns the text and value to a list box and matching it to the value in the listbox from the object like so:
MaterialDB materials = new MaterialDB();
DropDownList listBoxMaterials = new DropDownList();
listBoxMaterials.DataSource = materials.GetItems(ModuleId, TabId);
listBoxMaterials.DataBind();
string materialString = "";
foreach (ListItem i in listBoxMaterials.Items)
{
if (i.Value == row["MaterialTypeID"].ToString())
{
materialString = i.Text;
}
}
When I use this for the i.Value it always returns "System.Data.DataRowView" instead of the actual value. I'm doing this all in code behind. Anyway around this to get it to work?
Thanks!
You need to set the DataTextField and DataValueField properties of the DropDownList. Example:
MaterialDB materials = new MaterialDB();
DropDownList listBoxMaterials = new DropDownList();
listBoxMaterials.DataSource = materials.GetItems(ModuleId, TabId);
listBoxMaterials.DataTextField = "MaterialName";
listBoxMaterials.DataTextValue = "MaterialID";
listBoxMaterials.DataBind();
string materialString = "";
foreach (ListItem i in listBoxMaterials.Items)
{
if (i.Value == row["MaterialTypeID"].ToString())
{
materialString = i.Text;
}
}

How to keep selected item in listview when new items are added?

I am trying to make an application that lets me Check items in the ListView, and that all works fine, BUT if I add more items to the ListView while items are checked. It unchecks them all because the ListView is reloaded. Is there a way to get around this? So all of my items stay checked even when I add new ones to it? This is my current code.
TextReader reader = new StringReader(richTextBox1.Text);
string[] strItems = null;
foreach (ListViewItem items in listView1.Items)
{
items.Remove();
}
while (reader.Peek() != -1)
{
ListViewItem item = new ListViewItem();
strItems = reader.ReadLine().Split("-".ToCharArray());
item.Text = strItems[0].ToString();
item.SubItems.Add(strItems[1].ToString());
item.SubItems.Add(strItems[2].ToString());
item.SubItems.Add(strItems[3].ToString());
item.SubItems.Add(strItems[4].ToString());
listView1.Items.Add(item);
}
you can do something like that (and improve it a little by finding a better tag / exist logic):
TextReader reader = new StringReader(richTextBox1.Text);
string[] strItems = null;
while (reader.Peek() != -1)
{
string nextRow = reader.ReadLine();
if (!listView1.Items.ContainsKey(nextRow.GetHashCode().ToString()))
{
ListViewItem item = new ListViewItem();
item.Name = nextRow.GetHashCode().ToString();
strItems = nextRow .Split("-".ToCharArray());
item.Text = strItems[0].ToString();
item.SubItems.Add(strItems[1].ToString());
item.SubItems.Add(strItems[2].ToString());
item.SubItems.Add(strItems[3].ToString());
item.SubItems.Add(strItems[4].ToString());
listView1.Items.Add(item);
}
}
The only problem with that is if you are trying to delete items that won't be in the new read strings, but you can solve it too (tell me if you need it and i will add it)

How to make a listView item checked after comparing some string?

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

UltraWebGrid: How to use a drop-down list in a column

I'm using the Infragistics grid and I'm having a difficult time using a drop-down list as the value selector for one of my columns.
I tried reading the documentation but Infragistics' documentation is not so good. I've also taken a look at this discussion with no luck.
What I'm doing so far:
col.Type = ColumnType.DropDownList;
col.DataType = "System.String";
col.ValueList = myValueList;
where myValueList is:
ValueList myValueList = new ValueList();
myValueList.Prompt = "My text prompt";
myValueList.DisplayStyle = ValueListDisplayStyle.DisplayText;
foreach(MyObjectType item in MyObjectTypeCollection)
{
myValueList.ValueItems.Add(item.ID, item.Text); // Note that the ID is a string (not my design)
}
When I look at the page, I expect to see a drop-down list in the cells for this column, but my columns are empty.
Here's an example from one of my pages:
UltraWebGrid uwgMyGrid = new UltraWebGrid();
uwgMyGrid.Columns.Add("colTest", "Test Dropdown");
uwgMyGrid.Columns.FromKey("colTest").Type = ColumnType.DropDownList;
uwgMyGrid.Columns.FromKey("colTest").ValueList.ValueListItems.Insert(0, "ONE", "Choice 1");
uwgMyGrid.Columns.FromKey("colTest").ValueList.ValueListItems.Insert(1, "TWO", "Choice 2");
I've found what was wrong.
The column must allow updates.
uwgMyGrid.Columns.FromKey("colTest").AllowUpdate = AllowUpdate.Yes;
public void MakeCellValueListDropDownList(UltraWebGrid grid, string columnName, string valueListName, string[] listArray)
{
//Set the column to be a dropdownlist
UltraGridColumn Col = grid.Columns.FromKey(columnName);
Col.Type = ColumnType.DropDownList;
Col.DataType = "System.String";
try
{
ValueList ValList = grid.DisplayLayout.Bands[0].Columns.FromKey(columnName).ValueList;
ValList.DataSource = listArray;
foreach (string item in listArray)
{
ValList.ValueListItems.Add(item);
}
ValList.DataBind();
}
catch (ArgumentException)
{
}
}

Categories

Resources