By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,869 Members | 1,756 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,869 IT Pros & Developers. It's quick & easy.

ContextMenu does not work in DataGridView

P: n/a
I cant get a contextmenu to popup in the context of a datagridview. It
pops up in the ListBox, and in the form itself. But not the
DataGridView. How could that be?

here is my code:

using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace demo_DataGridView2
{

public partial class Form1 : Form
{
DataGridView mGrid1 = null ;
ContextMenu mContextMenu = null;
ListBox mListBox1 = null;

public Form1()
{
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Text = "Form1";
this.Width = this.Font.Height * 40;

mContextMenu = new ContextMenu();
mContextMenu.Popup += contextMenu_Popup;

mListBox1 = new ListBox();
mListBox1.Parent = this;
mListBox1.Location = new Point(10, 30);
mListBox1.Height = this.Font.Height * 5;
mListBox1.Width = this.Font.Height * 30;
mListBox1.Items.Add("line 0");
mListBox1.Items.Add("line 1");

mGrid1 = new DataGridView();
mGrid1.Parent = this;
mGrid1.Location = new Point(10, 120);
mGrid1.Height = this.Font.Height * 5;
mGrid1.Width = this.Font.Height * 30;
mGrid1.ColumnCount = 3;
mGrid1.AutoGenerateColumns = true;

string[] row1 = new string[3] {"col1", "col2", "col3"} ;
string[] row2 = new string[3] { "col1", "col2", "col3" };
mGrid1.Rows.Add(row1);
mGrid1.Rows.Add(row2);

this.ContextMenu = mContextMenu;
mListBox1.ContextMenu = mContextMenu;
mGrid1.ContextMenu = mContextMenu;
}

protected void contextMenu_Popup(System.Object InSender,
System.EventArgs InArgs)
{
mContextMenu.MenuItems.Clear();
if (mContextMenu.SourceControl == this)
{
mContextMenu.MenuItems.Add( new MenuItem("form menu item")) ;
}
else if (mContextMenu.SourceControl == mGrid1)
{
mContextMenu.MenuItems.Add( new MenuItem("grid menu item")) ;
}
else if (mContextMenu.SourceControl == mListBox1)
{
mContextMenu.MenuItems.Add(new MenuItem("ListBox menu item"));
}
}

} // end class Form1
} // end namespace demo_table

Aug 27 '07 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.