How to get item index from ListBox - c#

Currently using a Listbox and contextMenuStrip, after item right clicked how can the item's index be retrieved from the Listbox ?
My function:
private void contextMenuStripOption1_Click(object sender, EventArgs e)
{
if (listBoxFiles.SelectedIndex == -1)
{
return;
}
Point ptCursor = Cursor.Position;
int itemIndex = listBoxFiles.IndexFromPoint(ptCursor);
}
Delete function:
private void contextMenuStripDelete_Click(object sender, EventArgs e)
{
if (listBoxFiles.SelectedIndex == -1)
{
return;
}
listBoxFiles.Items.RemoveAt(listBoxFiles.SelectedIndex);
}

Do not assign the ContextMenuStrip to the ListBox; instead open it programmatically after you have determined the selected index
int _selectedIndex;
private void listBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right) {
_selectedIndex = listBox1.IndexFromPoint(e.Location);
if (_selectedIndex == -1) {
return;
}
contextMenuStrip1.Show(listBox1.PointToScreen(e.Location));
}
}
UPDATE:
Now you can access the index from the menu item clicks
private void contextMenuStripDelete_Click(object sender, EventArgs e)
{
listBoxFiles.Items.RemoveAt(_selectedIndex);
}
No need to recalculate the selected index and to test for -1. The context menu is not opened at all if the index is -1.

Use the container control: listBoxFiles.Items.IndexOf(listBoxFiles.SelectedItem)

Related

C# Drag and Drop in Listview doesn't work with Groups

I have a Listview with Drag and Drop codes working well.
However, after i add groups to it, the Drag and Drop codes are run, but the outcome is not what the codes used to behave.
Dropped items were only added to the tail of its group.
Why? and how to get it work properly with groups?
The Drag and Drop procedures are given herebelow:
private void lvQ_DragDrop(object sender, DragEventArgs e)
{
int targetIndex = lvQ.InsertionMark.Index;
if (targetIndex == -1)
return;
if (lvQ.InsertionMark.AppearsAfterItem)
targetIndex++;
ListViewItem draggedItem = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
if (targetIndex == 0 && lvQ.Items.OfType<ListViewItem>().FirstOrDefault()?.SubItems[1].Text == "FF")
{
lvQ.InsertionMark.Index = -1;
}
else
{
lvQ.BeginUpdate();
lvQ.Items.Insert(targetIndex, (ListViewItem)draggedItem.Clone());
lvQ.Items.Remove(draggedItem);
lvQ.EndUpdate();
ShowTXFrameStr();
}
}
private void lvQ_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.AllowedEffect;
}
private void lvQ_DragLeave(object sender, EventArgs e)
{
lvQ.InsertionMark.Index = -1;
}
private void lvQ_DragOver(object sender, DragEventArgs e)
{
Point ptScreen = new(e.X, e.Y);
Point pt = lvQ.PointToClient(ptScreen);
int targetIndex = lvQ.InsertionMark.NearestIndex(pt);
if (targetIndex > -1)
{
Rectangle itemBounds = lvQ.GetItemRect(targetIndex);
lvQ.InsertionMark.AppearsAfterItem = pt.Y > itemBounds.Top + (itemBounds.Height / 2);
}
lvQ.InsertionMark.Index = targetIndex;
}
private void lvQ_ItemDrag(object sender, ItemDragEventArgs e)
{
lvQ.DoDragDrop(e.Item, DragDropEffects.Move);
}

How to display the ContextMenuStrip when item is selected in a list box c# .net

I'm trying select an item from list box when is right clicked and show the ContextMenuStrip to display my options available, but when I click everywhere in the control (list box) is showing the ContextMenuStrip.
This is what I have in code:
private void lbSMTPEmails_MouseDown(object sender, MouseEventArgs e)
{
int SelectedIndex = lbSMTPEmails.IndexFromPoint(e.X, e.Y);
if (SelectedIndex == -1)
lbSMTPEmails.ContextMenuStrip.Hide();
else
{
lbSMTPEmails.SelectedIndex = SelectedIndex;
lbSMTPEmails.ContextMenuStrip.Show();
}
}
do you have any idea how to solve this?
Use opening event of ContextMenuStrip
void cms_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
int SelectedIndex = lbSMTPEmails.IndexFromPoint( lbSMTPEmails.PointToClient(Cursor.Position) );
if (SelectedIndex == -1)
e.Cancel = true;
else
{
lbSMTPEmails.SelectedIndex = SelectedIndex;
}
}
I did by this way and it worked!
private void listbox_MouseDown(object sender, MouseEventArgs e)
{
ShowMenuStrip = listbox.IndexFromPoint(e.Location) >= 0; //This is a global bool variable
if (ShowMenuStrip)
listbox.SelectedIndex = listbox.IndexFromPoint(e.Location);
else
listbox.SelectedIndex = -1;
}
private void ContextMenuStrip_Opening(object sender, CancelEventArgs e)
{
e.Cancel = !ShowMenuStrip;
}

Unable to drag and drop text from DataGridView to TextBox C#

I have been using code that others online have supplied but for some reason it won't let me drag items from the datagridview to the textbox. I highlight a row in the dataGridView and try to drag it to the textbox but nothing happens. I have also enabled the drop property for the textBox but still no difference. Here's the code that I am using:
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
DataGridView.HitTestInfo info = dataGridView1.HitTest(e.X, e.Y);
if (info.RowIndex >= 0)
{
if (info.RowIndex >= 0 && info.ColumnIndex >= 0)
{
string text = (String)
dataGridView1.Rows[info.RowIndex].Cells[info.ColumnIndex].Value;
if (text != null)
dataGridView1.DoDragDrop(text, DragDropEffects.Copy);
}
}
}
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
{
textBox1.Text = (System.String)e.Data.GetData(typeof(System.String));
}
}
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
Here is a small sample that i have done to give you an idea on how to do this... works perfectly for me. I used WinForms here. If WPF, there may be some more events you will need to register to in order for the drag+drop to register...
Note that you will want to add more code here and there to perform what you really want to do when you drag an item from one control to the other.
public partial class Form1 : Form
{
private Rectangle dragBoxFromMouseDown;
private int rowIndexFromMouseDown;
private int rowIndexOfItemUnderMouseToDrop;
private DataGridViewRow draggedrow;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<StringValue> Items = new List<StringValue>() { new StringValue("1"), new StringValue("2"), new StringValue("3"), new StringValue("4"), new StringValue("5"), new StringValue("6") };
this.dataGridView1.DataSource = Items;
}
private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
// If the mouse moves outside the rectangle, start the drag.
if (dragBoxFromMouseDown != Rectangle.Empty &&
!dragBoxFromMouseDown.Contains(e.X, e.Y))
{
// Proceed with the drag and drop, passing in the list item.
DragDropEffects dropEffect = dataGridView1.DoDragDrop(
dataGridView1.Rows[rowIndexFromMouseDown],
DragDropEffects.Move);
}
}
}
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
// Get the index of the item the mouse is below.
rowIndexFromMouseDown = dataGridView1.HitTest(e.X, e.Y).RowIndex;
if (rowIndexFromMouseDown != -1)
{
// Remember the point where the mouse down occurred.
// The DragSize indicates the size that the mouse can move
// before a drag event should be started.
Size dragSize = SystemInformation.DragSize;
// Create a rectangle using the DragSize, with the mouse position being
// at the center of the rectangle.
dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2),
e.Y - (dragSize.Height / 2)),
dragSize);
this.draggedrow = this.dataGridView1.CurrentRow;
}
else
// Reset the rectangle if the mouse is not over an item in the ListBox.
dragBoxFromMouseDown = Rectangle.Empty;
}
private void dataGridView1_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
this.textBox1.Text = (string)this.draggedrow.Cells["Value"].Value;
}
}
public class StringValue
{
public StringValue(string s)
{
_value = s;
}
public string Value { get { return _value; } set { _value = value; } }
string _value;
}
can't you use DataGridViewCellMouseEventArgs e instead of hittest for getting row index in dataGridView1_CellMouseDown. below is your code modified hope this helps
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (e.RowIndex >= 0)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
string text = (String)
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (text != null)
dataGridView1.DoDragDrop(text, DragDropEffects.Copy);
}
}
}
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
{
textBox1.Text = (System.String)e.Data.GetData(typeof(System.String));
}
}
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}

C# - Drag MenuStrip item to ListBox

I want to allow user to drag any item from MenuStrip to a ListBox.
I did it between to ListBoxes, but can not do it with MenuStrip.
Thanks a lot for your help.
I use WinForms, C#
For the destination ListBox I modified its property
this.listBox2.AllowDrop = true;
and created the following two events:
private void listBox2_DragOver(
object sender, System.Windows.Forms.DragEventArgs e)
{
e.Effect=DragDropEffects.All;
}
private void listBox2_DragDrop(
object sender, System.Windows.Forms.DragEventArgs e)
{
if(e.Data.GetDataPresent(DataFormats.StringFormat))
{
string str= (string)e.Data.GetData(
DataFormats.StringFormat);
listBox2.Items.Add(str);
}
}
What I need is what should be done to the source MenuStrip to allow drag items from it the ListBox, in over words how to make MenuStrip draggable.
Thanks to all for their help.
I found the solution:
The missing event is that I should add event to ToolStripMenuItem_MouseDown, I prefer to use right click instead of left click to avoid the conflict between ToolStripMenuItem_Click and the drag event, this the code:
AllowDrop = true;
private void tsmi_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
DoDragDrop(sender, System.Windows.Forms.DragDropEffects.Copy);
}
Add also this code to the ListView:
private void lvAllowDropListView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
System.Windows.Forms.ToolStripMenuItem button = e.Data.GetData(typeof(System.Windows.Forms.ToolStripMenuItem))
as System.Windows.Forms.ToolStripMenuItem;
if (button != null)
{
try
{
SmallImageList = sysIcons.SmallIconsImageList;
LargeImageList = sysIcons.LargeIconsImageList;
System.Windows.Forms.ToolStripMenuItem item = e.Data.GetData(typeof(System.Windows.Forms.ToolStripMenuItem))
as System.Windows.Forms.ToolStripMenuItem;
if (item != null)
{
AddToolStripMenuItem(item.Text, item.Name);
}
}
catch { }
}
}
private void AddToolStripMenuItem(string name, string tag)
{
System.Windows.Forms.ListViewItem item = new System.Windows.Forms.ListViewItem(name);
int Index = -1;
for (int i = 0; i < Items.Count;i++ )
if(Items[i].Tag.ToString() == tag)
{
Index = i;
break;
}
if (Index == -1)
{
item.Tag = tag;
Items.Add(item);
}
}
Drag Menu Strip Item is the same like ListBox item.
Check your code...

dataGridView Context menu function

I have added this code to my forum:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenu a = new ContextMenu();
a.MenuItems.Add(new MenuItem("Google"));
a.MenuItems.Add(new MenuItem("Yahoo"));
int currentMouseOverRow = dataGridView1.HitTest(e.X, e.Y).RowIndex;
if (currentMouseOverRow >= 0)
{
a.MenuItems.Add(new MenuItem(string.Format("", currentMouseOverRow.ToString())));
}
a.Show(dataGridView1, new Point(e.X, e.Y));
}
}
private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
currentMouseOverRow = e.RowIndex;
}
private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
currentMouseOverRow = -1;
}
But how do I add the function to the context menu option?
For google,
Process.Start("https://www.google.com");
For yahoo,
Process.Start("https://www.yahoo.com");
etc.
Why not add your ContextMenu right when your Form loads rather than every time that the user right click your DataGridView which means that you have to add the Context Menu every time the user rights click your DatGridView.
Secondly, instead of ContextMenu make a ContextMenuStrip instead which more at home with DataGridView. So, your code would look like:
ContextMenuStrip a = new ContextMenuStrip();
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}
void Form1_Load(object sender, EventArgs e)
{
Image img = null;
a.Items.Add("Google", img, new System.EventHandler(ContextMenuClick));
a.Items.Add("Yahoo", img, new System.EventHandler(ContextMenuClick));
dataGridView1.ContextMenuStrip = a;
}
Then your EventHandler would look like this:
private void ContextMenuClick(Object sender, System.EventArgs e)
{
switch (sender.ToString().Trim())
{
case "Google":
Process.Start("https://www.google.com");
break;
case "Yahoo":
Process.Start("https://www.yahoo.com");
break;
}
}
And your DataGridView Mouse Click handler would look this:
void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
int currentMouseOverRow = dataGridView1.HitTest(e.X, e.Y).RowIndex;
if (currentMouseOverRow >= 0)
{
a.Items.Add(string.Format("", currentMouseOverRow.ToString()));
}
a.Show(dataGridView1, new Point(e.X, e.Y));
}
}
You have to use ClickEvent for your menu items:
//menu items constructor
a.MenuItems.Add(new MenuItem("Google", new System.EventHandler(this.MenuItemClick)));
a.MenuItems.Add(new MenuItem("Yahoo", new System.EventHandler(this.MenuItemClick)));
private void MenuItemClick(Object sender, System.EventArgs e)
{
var m = (MenuItem)sender;
if (m.Text == "Google")
{
Process.Start("https://www.google.com");
}
}

Categories

Resources