I have two list box in WPF which looks something like this:
Lets say, the left one is lbLeft and right one is lbRight. The ">" button adds one selected item from lbLeft to lbRight. And, "<" removes the selected item form lbRight from the list. The ">>" adds all the item from lbLeft to lbRight and "<<" clears lbRight.
When I double click an item from lbLeft, it is added to the lbLeft and that newly added item is focused. Also, if i try to add an item from lbLeft which already exists in lbRight, it places a focus in that selected item(so that items are not repeated). But when lots of item are added in lbRight, I have to manually scroll down to the point where focus is placed. How can I make the scrolling of listbox automatic to the point where focus is placed?
I have done the following:
private void select_Click(object sender, RoutedEventArgs e) // > button
{
addingItemToSelectedList();
}
private void remove_Click(object sender, RoutedEventArgs e) // < button
{
if (lbRight.SelectedItem != null) {
lbRight.Items.RemoveAt(lbRight.SelectedIndex);
}
}
private void selectall_Click(object sender, RoutedEventArgs e) // >> button
{
lbRight.Items.Clear();
foreach (string item in column1) {
lbRight.Items.Add(item);
}
}
private void lbLeft_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
{
addingItemToSelectedList();
}
private void addingItemToSelectedList() {
if (lbLeft.SelectedItem != null)
{
string item = lbLeft.SelectedItem.ToString();
addFocus(item);
}
}
private void addFocus(string item) {
if (!lbRight.Items.Contains(item))
{
lbRight.Items.Add(item);
lbRight.SelectedIndex = lbRight.Items.Count - 1;
lbRight.Focus();
}
else
{
int index = lbRight.Items.IndexOf(item);
lbRight.SelectedIndex = index;
lbRight.Focus();
}
}
private void removeall_Click_1(object sender, RoutedEventArgs e) //<< button
{
lbRight.ItemsSource = null;
lbRight.Items.Clear();
}
column1 in the code is a list of items which populate lbLeft.
UPDATE:
I tried to use lbRight.ScrollIntoView(lbRight.SelectedIndex); But it has no effect
ScrollIntoView() worked now. What i had to do was:
lbRight.ScrollIntoView(lbRight.Items[lbRight.SelectedIndex]);
It now passes the actual item rather than index of it.
How do I get CheckBox.Checked item, my checkbox is inside listBox and listbox is binded with a class.
My class has two items: Name and Id
My code below:
I want that when I check on checkbox, in the background, I want Id of checked item.
private void CheckBox1_Checked(object sender, RoutedEventArgs e)
{
ListBoxItem checedItem = this.listBox1.ItemContainerGenerator.ContainerFromItem((sender as CheckBox).DataContext) as ListBoxItem;
if (checedItem != null)
{
checedItem.IsSelected = true;
}
}
May this help you.
private void CheckBox1_Checked(object sender, RoutedEventArgs e)
{
var checkBox = (CheckBox)sender;\
var data = (Your class)checkBox.DataContext;
var id = data.id;
}
I know how to make a contextMenu that pops up when I right click on a listView, what I want is for it to pop up when I right click on an item. I am trying to make a chat server and client, and now... Now I want to view client info when I right click on a connected client's item.
How can I do this?
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
var focusedItem = listView1.FocusedItem;
if (focusedItem != null && focusedItem.Bounds.Contains(e.Location))
{
contextMenuStrip1.Show(Cursor.Position);
}
}
}
You can put connected client information in the contextMenuStrip1. and when you right click on a item, you can show the information from that contextMenuStrip1.
You are going to have to use the ListViews Context Menu, but change it according to the ListView Item you right click on.
private void listView1_MouseDown(object sender, MouseEventArgs e)
{
bool match = false;
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
foreach (ListViewItem item in listView1.Items)
{
if (item.Bounds.Contains(new Point(e.X, e.Y)))
{
MenuItem[] mi = new MenuItem[] { new MenuItem("Hello"), new MenuItem("World"), new MenuItem(item.Name) };
listView1.ContextMenu = new ContextMenu(mi);
match = true;
break;
}
}
if (match)
{
listView1.ContextMenu.Show(listView1, new Point(e.X, e.Y));
}
else
{
//Show listViews context menu
}
}
}
You can trigger MouseDown or MouseUp event of ListView in which if MouseButton.Right then grab the selected Item by using ListView.Hittest and give the Context menu related to that Selected Item.
For more clear info you can go through this link
Fully solution
Pops up when user right click on a item in a listView.
Avoid an exception if the list have no items.
If an item was selected, display Delete and Edit options.
Code:
private void Form1_Load(object sender, EventArgs e)
{
listView1.MouseUp += new MouseEventHandler(listView1_MouseClick);
}
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
string id = "xxx";//extra value
if (e.Button == MouseButtons.Right)
{
if (listView1.FocusedItem != null && listView1.FocusedItem.Bounds.Contains(e.Location) == true)
{
ContextMenu m = new ContextMenu();
MenuItem cashMenuItem = new MenuItem("編輯");
cashMenuItem.Click += delegate (object sender2, EventArgs e2) {
ActionClick(sender, e, id);
};// your action here
m.MenuItems.Add(cashMenuItem);
MenuItem cashMenuItem2 = new MenuItem("-");
m.MenuItems.Add(cashMenuItem2);
MenuItem delMenuItem = new MenuItem("刪除");
delMenuItem.Click += delegate (object sender2, EventArgs e2) {
DelectAction(sender, e, id);
};// your action here
m.MenuItems.Add(delMenuItem);
m.Show(listView1, new Point(e.X, e.Y));
}
}
}
private void DelectAction(object sender, MouseEventArgs e, string id)
{
ListView ListViewControl = sender as ListView;
foreach (ListViewItem eachItem in ListViewControl.SelectedItems)
{
// you can use this idea to get the ListView header's name is 'Id' before delete
Console.WriteLine(GetTextByHeaderAndIndex(ListViewControl, "Id", eachItem.Index) );
ListViewControl.Items.Remove(eachItem);
}
}
private void ActionClick(object sender, MouseEventArgs e, string id)
{
//id is extra value when you need or delete it
ListView ListViewControl = sender as ListView;
foreach (ListViewItem tmpLstView in ListViewControl.SelectedItems)
{
Console.WriteLine(tmpLstView.Text);
}
}
public static string GetTextByHeaderAndIndex(ListView listViewControl, string headerName, int index)
{
int headerIndex = -1;
foreach (ColumnHeader header in listViewControl.Columns)
{
if (header.Name == headerName)
{
headerIndex = header.Index;
break;
}
}
if (headerIndex > -1)
{
return listViewControl.Items[index].SubItems[headerIndex].Text;
}
return null;
}
The topic is quite old, but I'll leave my solution for reference.
In xaml ListView definition put your context menu:
<ListView Name="m_list" >
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Header="menuItem1" Click="ContextMenuItem1Clicked" />
<MenuItem Header="menuItem2" Click="ContextMenuItem2Clicked" />
</ContextMenu>
</ListView.ContextMenu>
...
</ListView>
Now, in the code, define two event handlers that will fire up on clicking respective menu item:
private void ContextMenuItem1Clicked(object sender, RoutedEventArgs e)
{
// handle the event for the selected ListViewItem accessing it by
ListViewItem selected_lvi = this.m_list.SelectedItem as ListViewItem;
}
private void ContextMenuItem2Clicked(object sender, RoutedEventArgs e)
{
// handle the event for the selected ListViewItem accessing it by
ListViewItem selected_lvi = this.m_list.SelectedItem as ListViewItem;
}
ListView can accommodate objects, which means that the selected_lvi can be of type of your object. Just cast is to proper type.
I hope this helps.
Best regards,
Mike
I've found a new solution that doesn't rely on mouse event handlers.
The ContextMenu has a "Popup" event handler.
On popup, I add the relevant menu items I need depending on my context.
Example :
private MenuItem[] standardMenuItems;
private MenuItem[] selectedMenuItems;
public SomePanel() {
InitializeComponent();
// These are list of menu items (name / callback) that will be
// chosen depending on some context
standardMenuItems = new MenuItem[] { new MenuItem("New", OnNew) };
selectedMenuItems = new MenuItem[] { new MenuItem("Delete", OnDelete), new MenuItem("Edit", OnEdit) };
ContextMenu contextMenu = new ContextMenu();
// begin with "standard items"
contextMenu.MenuItems.AddRange(standardMenuItems);
listview.ContextMenu = contextMenu;
// add the popup handler
contextMenu.Popup += OnMenuPopup;
}
// Called right before the menu comes up
private void OnMenuPopup(object sender, EventArgs e) {
ContextMenu menu = sender as ContextMenu;
if (menu == null)
return;
// If an item was selected, display Delete and Edit options
if (listview.SelectedItems.Count > 0) {
menu.MenuItems.Clear();
menu.MenuItems.AddRange(selectedMenuItems);
}
// Else display only the New option
else {
menu.MenuItems.Clear();
menu.MenuItems.AddRange(standardMenuItems);
}
}
I'm not fluent enough in C# and Winforms to be sure there are no drawbacks to this technique, but it's an alternative to relying on mouse events (what if / does the context menu can appear on other keyboard or mouse event ?)
private void contextMenuStripExport_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
if (exportview.SelectedItems.Count <= 0)
{
uploadToolStripMenuItem.Visible = false;
exportToolStripMenuItem.Visible = false;
}
else
{
uploadToolStripMenuItem.Visible = true;
exportToolStripMenuItem.Visible = true;
}
}
Using DevExpress 20.2 Core... Winforms. This is similar to handling a menu item in a GridView.
Private WithEvents _menuViewLabelitem As MenuItem
Private Sub lvShipTracking_MouseClick(sender As Object, e As MouseEventArgs) Handles lvShipTracking.MouseClick
If e.Button = MouseButtons.Right Then
If lvShipTracking.FocusedItem IsNot Nothing AndAlso lvShipTracking.FocusedItem.Bounds.Contains(e.Location) = True Then
Dim m As ContextMenu = New ContextMenu()
_menuViewLabelitem = New MenuItem("View Label")
AddHandler Click, AddressOf Handle_ViewLabel
m.MenuItems.Add(_menuViewLabelitem)
m.Show(lvShipTracking, New Point(e.X, e.Y))
End If
End If
End Sub
Private Sub Handle_ViewLabel(sender As Object, e As EventArgs) Handles _menuViewLabelitem.Click
MsgBox("it worked!")
End Sub
I have a listBox1 with 4 items inside. I can use the keys to move up-down between the items or click with the mouse once on each item in both cases the selected items will be highlight with blue marked .
I want when I click on an item or when I move the keys up and down over the items it will change the label.Text with the current item name.
For example in on the item moses so label1.Text will contain moses.
Moved to the next item with arrow key up so now label1.Text contain daniel.
Clicked with the mouse on the item number 3 now label1.Text will contain dana.
Tried with this:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
//listBox1.Items.Add(fsi[i].Name + Environment.NewLine);
label2.Text = listBox1.Items[i].ToString();
}
}
But its not worrking.
Works for me.
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add("Item1");
listBox1.Items.Add("Item2");
listBox1.Items.Add("Item3");
listBox1.Items.Add("Item4");
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = listBox1.SelectedItem.ToString();
}
You really expected your code to work? Why iterate over the whole collection, if you just need to check for the currently selected item?
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);
label2.Text = lbi.Content.ToString();
}
or if you're using webforms:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label2.Text = listBox1.SelectedItem.Text;
}
If you are using List<CustomClass>/ObservableCollection<CustomClass> as ItemSource for ListBox try the following way in listbaox selected index changed event
var listTapped = sender as ListBox;
var selectedUser = listTapped.SelectedItem as CustomClass;
if (selectedUser == null)
return;
label2.Text = selectedUser.Name; //
ListBox contains event SelectedIndexChanged. It raises on such conditions. I think you should use it. Then you should use SelectedValue property to get correct string.
I have a contextmenu control on a listview, although I am trying to obtain the value of selected item in the listview when I right hand click on it - I have looked on numerous sources and have not found anything to convincing
private void startCheckToolStripMenuItem_Click(object sender, EventArgs e)
{
}
Just cast the sender to ListBox (assuming that's what was right clicked) and then you can iterate through selected items.
var lbx = sender as ListBox;
foreach (var item in lbx.SelectedItems) ...
[Hand keyed, so may be capitilization errors etc]
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
ListView listView = sender as ListView;
this.contextMenuStrip1.Items.Clear();
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
ListViewItem item = listView.GetItemAt(e.X, e.Y);
if (item != null)
{
this.contextMenuStrip1.Items.Add(item.Text);
item.Selected = true;
contextMenuStrip1.Show(listView, e.Location);
}
}
}