Reputation: 1498
I have a ListView with 2 columns. For example's sake, we'll say it looks like this:
ColA | ColB
-----------------
001 |
002 |
003 |
004 |
005 |
I have a text file that contains the following lines:
001
002
004
005
008
I'm trying to read through the file line by line, and if the number matches a number in ColumnA, I want to add it to ColumnB. That works fine (see my example below). However, I'd also like to add any non-matches as a new ListViewItem. I can't figure that part out. Here's what I have so far:
foreach (string textfileitem in TheTextFile)
{
foreach (ListViewItem item in ListView1.Items)
{
var existingitem = item.SubItems[0];
if (existingitem.Text == textfileitem)
{
item.SubItems[1].Text = textfileitem;
}
}
}
I'm not sure how to handle any non-matches and add them to the ListView. the end result would look like this:
ColumnA | ColumnB
-----------------
001 | 001
002 | 002
003 |
004 | 004
005 | 005
- | 008
As always, your help is appreciated!
Upvotes: 0
Views: 135
Reputation: 1498
Based on @Neolisk 's suggestion, I rethought my process and ended up using a DataGridView
bound to a DataTable
. ColumnA gets populated by data in the DataTable
. Then, I put each item in ColumnA into a Dictionary
.
My code now looks like this:
int count;
Dictionary<string, int> d = new Dictionary<string, int>();
foreach (DataRow dr in dataSet1.Tables["Table1"].Rows)
{
d.Add((string)dr[0], count);
count++;
}
foreach (string textfileitem in TheTextFile)
{
string item = //specific data from textfileitem
int value;
if (d.TryGetValue(item, out value)
{
DataRow[] dr = dataSet1.Tables["Table1"].Select("ColumnA = " + item");
dr[0]["ColumnB"] = item;
}
else
{
dataTable1.Rows.Add(null, item);
}
}
At least I hope that's accurate. I tried to make my code generic and get rid of the non-essential stuff.
Upvotes: 0
Reputation: 151
I would do something like this:
List<string> listItems = ListView1.Items.Select(item => item[0].ToString()) // Get list of current items
foreach (string textItem in TheTextFile.Except(listItems)) { // Get all text items that are not in the current list
// Add missing list view item
}
Upvotes: 0
Reputation: 9639
Here is another way to do it:
List<string> missingItems = new List<string>();
foreach (string textfileitem in TheTextFile)
{
foreach (ListViewItem item in ListView1.Items)
{
var existingitem = item.SubItems[0];
if (existingitem.Text == textfileitem)
{
item.SubItems[1].Text = textfileitem;
}
else
{
missingItems.Add(textfileitem);
}
}
}
foreach (string missingItem in missingItems)
{
// Add missing item to your ListView.
ListView1.Items.Add("missing").SubItems.Add(missingItem);
}
Upvotes: 0
Reputation: 26424
Run through your columnA
, create a dictionary of <String,YourDataSourceItem>
. Run through your file - test match using TryGetValue
. If found, set columnB
. If not, create a new item.
Upvotes: 1