Copy selected items from ListView1 to ListView2 - c#

Could someone please point me in the right direction?
I have got one populated ListView and trying to get the selected items into another ListView. The code I've got doesn't produce any errors, neither does it
display any of the selected items.
Thanks in advance.
private void button3_Click(object sender, EventArgs e){
string s = " Search Via Forename";
int result = 0;
int count = 0;
result = string.Compare(textBox1.Text, s);
if ((result == 0) || (String.IsNullOrEmpty(textBox1.Text))){
MessageBox.Show("Please input forename...");
return;
}
foreach (ListViewItem item in listView1.Items){
if (item.Text.ToLower().StartsWith(textBox1.Text.ToLower())){
count++;
item.BackColor = Color.DodgerBlue;
item.ForeColor = Color.White;
statusBar1.Panels[2].Text = "Found: " + count.ToString();
} else {
item.BackColor = Color.White;
item.ForeColor = Color.Black;
}
}
if (count > 1){
listView2.Visible = true;
foreach (ListViewItem item in listView1.Items){
listView2.Items.Add((ListViewItem)item.Clone());
}
}
}

if (count > 1){ should be if (count > 0){ or if (count >= 1){ ... in case there is only one match present. Moreover, don't see you are adding selected items

why dont you do the clone directly in the first foreach?
foreach (ListViewItem item in listView1.Items)
if(item.Text.ToLower().StartsWith(textBox1.Text.ToLower()))
listView2.Items.Add((ListViewItem)item.Clone());
As you are doing it now, you dont select any item in the first list, only changing colors. Try using the SelectedIndices or SelectedItems properties.

Related

Multi Column Search in a ListView

Ok... so I have got a working procedure to search a ListView. This procedure
works successfully however, it only searches 1 of 5 columns. My desire is to
get the procedure to search the first 2 columns which are forename and surname. I found a line of code which is suppose to do it but after compilation, it produces an error. Below is an excerpt of my code. and the line I am trying to use.
Thanks in advance for all the help and advice
private void button3_Click(object sender, EventArgs e)
{
string s = " Search Via Forename";
int result = 0;
int count = 0;
result = string.Compare(textBox1.Text, s);
if ((result == 0) || (String.IsNullOrEmpty(textBox1.Text)))
{
MessageBox.Show("Please input forename...");
return;
}
foreach(ListViewItem.ListViewSubItem subItem in item.SubItems)
{
if (item.Text.ToLower().StartsWith(textBox1.Text.ToLower()))
{
count++;
statusBar1.Panels[2].Text = "Found: " + count.ToString();
}
else
{
listView1.Items.Remove(item);
}
}
button1.Text = "Clear";
textBox1.Visible = false;
button3.Visible = false;
button2.Visible = false;
}
This happens because you are referencing an undeclared variables called item that was never declared or instanciated.
When looping through the list items, you need to use:
foreach(ListViewItem item in listView1.Items)
This will iterate the ListView's Items with a variable called item that will hold the current item on each iteration.
Try this code:
private void button3_Click(object sender, EventArgs e)
{
string s = " Search Via Forename";
int result = 0;
int count = 0;
result = string.Compare(textBox1.Text, s);
if ((result == 0) || (String.IsNullOrEmpty(textBox1.Text)))
{
MessageBox.Show("Please input forename...");
return;
}
foreach(ListViewItem item in listView1.Items)
{
if (item.Text.ToLower().StartsWith(textBox1.Text.ToLower()))
{
count++;
statusBar1.Panels[2].Text = "Found: " + count.ToString();
}
else
{
listView1.Items.Remove(item);
}
}
button1.Text = "Clear";
textBox1.Visible = button3.Visible = button2.Visible = false;
}

Remove highlight from ListView items....deselecting

Basically I am writing a simple phone directory. This application has a listview window, a search (text) window and a button to search. Once the user inputs a name in the search window and hit the search button, the program selects and highlight all users corresponding to the search criteria.
No problem….
A unique scenario developed however if the user selects another item in the listview window. The previous items found are/will be still highlighted…
How can I deselect/remove the highlight on the found items whenever/ifever the user select another item immediately after the search?
Below is the code attached to the search button:
Thanks in advance
private void button3_Click(object sender, EventArgs e){
string s = " Search Via Forename";
int result = 0;
int count = 0;
result = string.Compare(textBox1.Text, s);
switch ((result == 0) || (String.IsNullOrEmpty(textBox1.Text))){
case true: MessageBox.Show("Please input forename...");
break;
default: foreach (ListViewItem item in listView1.Items){
if (item.Text.ToLower().StartsWith(textBox1.Text.ToLower())){
item.Selected = true;
item.BackColor = Color.CornflowerBlue;
item.ForeColor = Color.White;
count++;
}else{
item.Selected = false;
item.BackColor = Color.White;
item.ForeColor = Color.Black;
}
}
if (listView1.SelectedItems.Count == 1){
listView1.Focus();
}
textBox1.Text = " Search Via Forename";
textBox1.ForeColor = Color.Silver;
break;
}
}
Before your highlightning code, make a loop through all the items and set their item.Selected to false.
foreach (ListViewItem item in listView1.Items){
if (item.Selected)
item.Selected = false;
}
First removed the selection piece of your code. In fact I would just clear selections all together. The color change that your doing is effectively doing the highlighting for you, so from the information you've provided I don't think its necessary to select them.
private void button3_Click(object sender, EventArgs e){
string s = " Search Via Forename";
int result = 0;
int count = 0;
result = string.Compare(textBox1.Text, s);
switch ((result == 0) || (String.IsNullOrEmpty(textBox1.Text))){
case true: MessageBox.Show("Please input forename...");
break;
default: foreach (ListViewItem item in listView1.Items){
item.Selected = false;
if (item.Text.ToLower().StartsWith(textBox1.Text.ToLower())){
item.BackColor = Color.CornflowerBlue;
item.ForeColor = Color.White;
count++;
}else{
item.BackColor = Color.White;
item.ForeColor = Color.Black;
}
}
if (listView1.SelectedItems.Count == 1){
listView1.Focus();
}
textBox1.Text = " Search Via Forename";
textBox1.ForeColor = Color.Silver;
break;
}
}
Next I would use the selection changed event to detect when a selection was made and clear all the formatting I did.
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListViewItem item in listView1.Items)
{
item.BackColor = Color.White;
item.ForeColor = Color.Black;
}
}
You didn't specify win forms or WPF so I assumed win forms and made an example that way. If your using WPF i believe the event you would need to subscribe to is the OnSelectionChanged event for the list view control.
After looking at the code a bit more, I realize your using a switch statement to handle a Boolean operation which is not correct. I've added how I would have changed that check below.
private void button3_Click(object sender, EventArgs e)
{
string s = " Search Via Forename";
int result = 0;
int count = 0;
result = string.Compare(textBox1.Text, s);
// Do the check on the input
if ((result == 0) || (string.IsNullOrEmpty(textBox1.Text)))
{
MessageBox.Show("Please input forename...");
// after notifying the user just return
return;
}
foreach (ListViewItem item in listView1.Items)
{
item.Selected = false;
if (item.Text.ToLower().StartsWith(textBox1.Text.ToLower()))
{
item.BackColor = Color.CornflowerBlue;
item.ForeColor = Color.White;
count++;
}
else
{
item.BackColor = Color.White;
item.ForeColor = Color.Black;
}
}
if (listView1.SelectedItems.Count == 1)
{
listView1.Focus();
}
}

Fill Data in Listbox with another Listbox which is having Data-Bound

I have this two list-box In that first list-box is fill on Combo-box Selected index changed, so List-box 1 is Bounded. Now when I press the > button all selected item in List-box 1 is display in List-box 2.
But instead of Names, I get System.Data.DataRowView
so my question is I want Names instead of this System.Data.DataRowView
my code is this
private void btnSelect1ItemFrom_Click(object sender, EventArgs e)
{
if (listBoxSelectToLedger.Items.Count > 0)
{
for (int i = 0; listBoxSelectToLedger.Items.Count > i; )
{
listBoxSelectToLedger.Items.Remove(listBoxSelectToLedger.Items[i].ToString());
}
}
if (listBoxSelectFromLedger.SelectedItem != null)
{
** for (int i = 0; i < listBoxSelectFromLedger.SelectedItems.Count; i++)
{
listBoxSelectToLedger.Items.Add(listBoxSelectFromLedger.SelectedItems[i].ToString());
} **
}
else
{
MessageBox.Show("No item Selected");
}
* I think I am some where Wrong in Second IF Condition in my Code *
Plz Help me
Thanks in Advance
Try this...
private void button1_Click(object sender, EventArgs e)
{
if(listBoxFrom.SelectedItems.Count>0)
{
for (int x = listBoxFrom.SelectedIndices.Count - 1; x >= 0; x--)
{
int idx = listBoxFrom.SelectedIndices[x];
listBoxTo.Items.Add(listBoxFrom.Items[idx]);
listBoxFrom.Items.RemoveAt(idx);
}
}
}
Hiii.. Deep, use the below code to add ListItem.
foreach (ListItem LI in listBoxFrom.Items)
{
if (LI.Selected)
listBoxTo.Items.Add(LI);
}
To add in to 2nd listbox and remove that from the first listbox you can use below code:
int[] indices = listBoxFrom.GetSelectedIndices();
for (int i = indices.Length - 1; i >= 0; i--)
{
ListItem LI = listBoxFrom.Items[indices[i]];
listBoxTo.Items.Add(LI);
listBoxFrom.Items.RemoveAt(indices[i]);
}
put your No items selected message where you require.
I got answer of my own question.
i have to set my DataRowView object
if (listBoxSelectToLedger.Items.Count > 0)
{
for (int i = 0; listBoxSelectToLedger.Items.Count > i; i = 0)
{
listBoxSelectToLedger.Items.Remove(listBoxSelectToLedger.Items[i].ToString());
}
}
if (listBoxSelectFromLedger.SelectedItem != null)
{
foreach (DataRowView objDataRowView in listBoxSelectFromLedger.SelectedItems)
{
listBoxSelectToLedger.Items.Add(objDataRowView["item_name"].ToString());
}
}
else
{
MessageBox.Show("No Item selected");
}

Clear contents of specific listview columns?

This is how I currently add info to my listview:
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
int totItems = Seq3.Count - 1;
if (PercentPopTolerance1.Count - 1 > totItems) totItems = PercentPopTolerance1.Count - 1;
for (int i = 0; i <= totItems; i++)
{
ListViewItem lvi = new ListViewItem();
string item1 = "";
string item2 = "";
if (Seq3.Count - 1 >= i) item1 = Seq3[i].ToString();
if (PercentPopTolerance1.Count - 1 >= i) item2 = PercentPopTolerance1[i].ToString();
lvi.SubItems.Add(item1);
lvi.SubItems.Add(item2);
listView2.Items.Add(lvi);
}
}
View of empty listview:
Now how would I clear the contents of any particular column? Say I want to add to column YYMM but before I do this, I want to clear that particular column. How would this be done?
You can clear column values like this
var items = listView1.Items;
foreach (ListViewItem item in items)
{
a.SubItems["YYWW"].Text = "";
}
You should specify a column by its name (a column corresponds to a subitem in a ListViewItem), note that this Name is not ColumnHeader.Name, I mean the corresponding ListViewSubItem.Name:
public void ClearColumn(string colName){
foreach(ListViewItem item in listView1.Items){
var cell = item.SubItems[colName];
if(cell != null) cell.Text = "";
}
}
The following code will work for ColumnHeader.Name passed in instead of ListViewSubItem.Name as the code above does:
public void ClearColumn(string columnHeaderName){
int i = listView1.Columns.IndexOfKey(columnHeaderName);
if(i == -1) return;
foreach(ListViewItem item in listView1.Items){
item.SubItems[i].Text = "";
}
}
You can try the following code to make it work for Text instead of Name:
public void ClearColumn(string colText){
if(listView1.Items.Count == 0) return;
var col = listView1.Columns.Cast<ColumnHeader>()
.Select((x,i)=>new{x,i})
.FirstOrDefault(a=>a.x.Text == colText);
if(col == null) return;
foreach(ListViewItem item in listView1.Items){
item.SubItems[col.i].Text = "";
}
}

How do I determine if multiple items are selected in a ListBox

I think it's obvious what I'm trying to do, but if you don't understand, please ask.
if (listBox1.SelectedIndex == 1 && 2)
{
label1.Text = "Sometext";
}
SelectedIndices is what you want if you have enabled multi-select. You can also check the size of the SelectedItems property.
The documentation for ListBox.SelectedIndex states:
For a standard ListBox, you can use this property to determine the index of the item that is selected in the ListBox. If the SelectionMode property of the ListBox is set to either SelectionMode.MultiSimple or SelectionMode.MultiExtended (which indicates a multiple-selection ListBox) and multiple items are selected in the list, this property can return the index to any selected item.
Try this
if( listBox1.SelectedItems.Count > 1 )
{
// multiple items are selected
}
if (listBox1.SelectedIndices.Count > 1) // I'd use to group all of your multi-selection cases
{
if (listBox1.SelectedIndices.Contains(1) && listBox1.SelectedIndices.Contains(2))
{
label1.Text = "Sometext";
}
}
Keep in mind that the control is 0 based so if you're trying to select the first two options, you'll want to check for 0 (item 1) and 1 (item 2).
edit: modified to handle the requirement listed in comments. Note, there's probably a better way and there may even be a method for this built in (never used the multi-selection list box). But I built a function to handle so you don't have to do it for every scenario.
The function that does the work:
private bool CasesFunction(ListBox lbItem, List<int> validIndices)
{
for (int index = 0; index < lbItem.Items.Count; index++)
{
if (lbItem.SelectedIndices.Contains(index) && !validIndices.Contains(index))
return false;
}
return true;
}
And how I used it:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndices.Count > 1)
{
List<int> MyCase = new List<int> { 0, 1 };
if (CasesFunction(listBox1, MyCase))
{
label1.Text = "Sometext";
return;
}
else
label1.Text = "";
MyCase = new List<int> { 1, 2 }; // can do other checks
if (CasesFunction(listBox1, MyCase))
{
label1.Text = "Sometext 2";
return;
}
else
label1.Text = "";
}
else
label1.Text = listBox1.SelectedIndex.ToString();
}

Categories

Resources