Am creating a context menu programmatically as to have right click options on my datagrid. Here is my code:
public partial class Form1 : Form
{
//string fileExcel;
public Form1()
{
InitializeComponent();
fillCari();
FillCombo();
ContextMenuStrip mnu = new ContextMenuStrip();
ToolStripMenuItem mnuCopy = new ToolStripMenuItem("Copy");
ToolStripMenuItem mnuCut = new ToolStripMenuItem("Cut");
ToolStripMenuItem mnuPaste = new ToolStripMenuItem("Paste");
//Assign event handlers
mnuCopy.Click += new EventHandler(mnuCopy_Click);
mnuCut.Click += new EventHandler(mnuCut_Click);
mnuPaste.Click += new EventHandler(mnuPaste_Click);
//Add to main context menu
mnu.Items.AddRange(new ToolStripItem[] { mnuCopy, mnuCut, mnuPaste });
//Assign to datagridview
dataGridView1.ContextMenuStrip = mnu;
}
This particular block I keep getting the error that it does not exist in current context. Any idea why?
mnuCopy.Click += new EventHandler(mnuCopy_Click);
mnuCut.Click += new EventHandler(mnuCut_Click);
mnuPaste.Click += new EventHandler(mnuPaste_Click);
Updated question:I created the strips from the context menu but not sur ehow to implement the copy commands.
public partial class Form1 : Form
{
//string fileExcel;
public Form1()
{
InitializeComponent();
fillCari();
FillCombo();
ContextMenuStrip mnu = new ContextMenuStrip();
dataGridView3.ContextMenuStrip = mnu;
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
}
I had figured it out for awhile now. Hopefully it helps anyone in the future. Keep in mind after creating your contextMenuStrip and adding a "copy" field to the strip you will then bind it to the dataGridView. This is done by going into properties of the context menu and looking for the dataGridView name and bind it to it. After that open the click event in properties on the contextMenu and add this code in it:
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
dataGridView3.Select();
DataObject o = dataGridView3.GetClipboardContent();
Clipboard.SetDataObject(o);
}
You should now have your right click copy button working.
For the click event you need event handlers:
// event click
mnuCopy.Click += new EventHandler(mnuCopy_Click);
mnuCut.Click += new EventHandler(mnuCut_Click);
mnuPaste.Click += new EventHandler(mnuPaste_Click);
// event handler method
void mnuPaste_Click(object sender, EventArgs e) {
// paste logic
}
void mnuCut_Click(object sender, EventArgs e) {
// cut logic
}
void mnuCopy_Click(object sender, EventArgs e) {
// copy logic
}
Related
I am new to C# and I am using windows forms.
I have flowLayoutPanel and I programmatically add some buttons to it .
What I am trying to do is: I want to save the first button located in the flowLayoutPanel into ButtonToSave object.
flowLayoutPanel1.FlowDirection= FlowDirection.LeftToRight
private void AddButtons_Click(object sender, EventArgs e)
{
Button btn = new Button();
flowLayoutPanel1.Controls.Add(btn);
}
private void StoreTheFirstButton_Click(object sender, EventArgs e)
{
Button ButtonToSave = new Button();
ButtonToSave = "First button in flowLayoutPanel1"
}
Anyone knows how to save the first button located in flowLayoutPanel1 into ButtonToSave when StoreTheFirstButton event is raised?
Thank you
Try code below. You may want to look at my response at following posting (How to (create and) add components to a Table Layout?) :
private void AddButtons_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn.Click += new EventHandler(StoreTheFirstButton_Click);
flowLayoutPanel1.Controls.Add(btn);
}
private void StoreTheFirstButton_Click(object sender, EventArgs e)
{
Button button = sender as Button;
Button ButtonToSave = button;
//ButtonToSave = "First button in flowLayoutPanel1";
}
I have this situation I want to synchronize informations in my dataGridView when I insert it on my add form like you can see on this picture.
In my Insert form on insert button I call Add form to pop up like this
private void button1_Click(object sender, EventArgs e)
{
if (addForm==null)
{
addForm = new AddForm();
}
addForm.MdiParent = this.ParentForm;
addForm.FormClosed += AddForm_FormClosed;
addForm.Show();
}
private void AddForm_FormClosed(object sender, FormClosedEventArgs e)
{
addForm = null;
}
On Add form in Accept click I insert informations and call fillDataGrid() method from Insert form to do data sync but nothing is shown data is shown just when I close Insert form and call it again does someone has susggestion how can I do this this is the first time I work with MdiContainer ?
private void buttonAccept_Click(object sender, EventArgs e)
{
if (validation())
{
Proizvod product = new Proizvod();
product.NazivProizvoda = textBoxName.Text;
product.Opis = textBoxDescription.Text;
product.SerijskiBroj = textBoxNumber.Text;
product.ZemljaPorijekla = textBoxCountry.Text;
if (pDal.insertProduct(product)==0)
{
MessageBox.Show("Informations are successfully inserted","Message");
InsertForm inForm = new InsertForm();
inForm.fillDataGrid();
}
}
}
My fillDataGrid() method and Load event of InsertForm:
public void fillDataGrid()
{
dataGridViewProducts.DataSource = null;
dataGridViewProducts.AutoGenerateColumns = false;
dataGridViewProducts.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewProducts.ColumnCount = 3;
dataGridViewProducts.Columns[0].Name = "Product name";
dataGridViewProducts.Columns[0].DataPropertyName = "NazivProizvoda";
dataGridViewProducts.Columns[1].Name = "Country";
dataGridViewProducts.Columns[1].DataPropertyName = "ZemljaPorijekla";
dataGridViewProducts.Columns[2].Name = "Product number";
dataGridViewProducts.Columns[2].DataPropertyName = "SerijskiBroj";
dataGridViewProducts.DataSource = pDal.getAllProducts();
}
private void InsertForm_Load(object sender, EventArgs e)
{
fillDataGrid();
}
private void InsertForm_Shown(object sender, EventArgs e)
{
dataGridViewProducts.CurrentCell = null;
dataGridViewProducts.ClearSelection();
}
Currently in buttonAccept_Click code, you have created a new instance of the list form and called its FillGrid. This way you are manipulating another instance of the list form which is different from the instance which is open and you can see. You are filling a different form which you didn't show it.
Instead of creating a new instance, create a constructor for your second form which accepts a parameter of first form type. Then when you want to create a new instance of seccod form, pass the instance of the first form (this) to second Form. Then in your save button call the FillGrid method of the passed instance.
For more information about how to manipulate another form, read this post. It contains some useful options about:
Pass data to second Form when creating
Manipulate second Form after showing
Manipulate first Form from second Form
Here is some code which belong to the ListForm:
private void ShowAddForm_Click(object sender, EventArgs e)
{
if (addForm == null)
{
addForm = new AddForm(this);
addForm.MdiParent = this.ParentForm;
addForm.FormClosed += AddForm_FormClosed;
}
addForm.Show();
}
private void AddForm_FormClosed(object sender, FormClosedEventArgs e)
{
addForm = null;
}
And here is the code for AddForm
public class AddForm
{
MyListForm listForm;
public AddForm(MyListForm f)
{
InitializeComponent();
listForm = f;
}
private void SaveVutton_Click(object sender, EventArgs e)
{
//perform validation and save data
f.FillGrid();
}
}
I have a data grid view whose data source gets assigned a list of items after the following function on load:
public void refreshGrid(object sender, FormClosingEventArgs e)
{
dgvItems.SuspendLayout();
itemBindingSource.SuspendBinding();
List<Item> items = db.Items.ToList(); // db is MyContext db = new MyContext();
itemBindingSource.DataSource = items;
dgvItems.DataSource = null;
dgvItems.DataSource = itemBindingSource;
itemBindingSource.ResumeBinding();
dgvItems.ResumeLayout();
}
private void AllItemsForm_Load(object sender, EventArgs e)
{
refreshGrid();
}
and there is a edit button which does the following on click:
private void btnEditItem_Click(object sender, EventArgs e)
{
Item item = (Item)dgvItems.SelectedRows[0].DataBoundItem;
var editForm = new EditItemForm(item);
editForm.FormClosing += new FormClosingEventHandler(refreshGrid);
editForm.Show();
}
i.e. opens an edit form and assigns refreshGrid() to its closing event.
On that Edit Form I have this Save button which does this:
private void btnSave_Click(object sender, EventArgs e)
{
Item itemEdited = db.Items.Where(i => i.itemId == itemEditing.itemId).Single();
itemEdited.categoryId = (int)cbxCategory.SelectedValue;
itemEdited.description = tbxDescription.Text;
itemEdited.price = (Double)nudPrice.Value;
db.Entry(itemEdited).State = EntityState.Modified;
db.SaveChanges();
this.Close();
}
the item edit is working, but is apparent only after closing and reopening the edit form, i.e. that refreshGrid() method which was assigned to its closing event is not working!
How can I fix this?
I found my own mistake. The mistake was using two different instances of Context class.
The solution was to add:
SomsaContext database = new SomsaContext(); // i.e. new instance of Context class
right before the refresh takes place.
I've added 4 menus in context menu. If during the start context menu item is clicked, how to disable that particular ("Start") menu item?
ContextMenu conMenu1 = new ContextMenu();
public Form1()
{
InitializeComponent();
conMenu1.MenuItems.Add("Start", new System.EventHandler(this.Start_Click));
conMenu1.MenuItems.Add("Pause", new System.EventHandler(this.Pause_Click));
conMenu1.MenuItems.Add("Resume", new System.EventHandler(this.Resume_Click));
conMenu1.MenuItems.Add("Stop", new System.EventHandler(this.Stop_Click));
}
private void Start_Click(object sender, EventArgs e)
{
// Functionalities to disable start context menu item
}
You can do like this. Handle the ContextMenu.Opening Event
private void conMenu1_Opening(object sender, CancelEventArgs e)
{
conMenu1.Items[0].Enabled= false;
}
Use PopUp event such as
Declaration
var trayMenu = new ContextMenu();
trayMenu.Popup += MenuOpening;
trayMenu.MenuItems.Add(...);
...
Subscribed Event
private void MenuOpening(object sender, EventArgs e)
{
var cm = sender as ContextMenu;
if (cm != null)
cm.MenuItems[0].Enabled = false;
}
I'm putting together a simple UI that interacts with a SQL database. My problem is a UI problem, ever time a menustrip item is selected, it opens a new active window. How do I set this up to close the previous active window? I've tried using Form.Close();, but that just closes everything.
private void addCampusToolStripMenuItem_Click(object sender, EventArgs e)
{
if_add_campus go = new if_add_campus();
go.Show();
}
private void addDepartmentToolStripMenuItem_Click(object sender, EventArgs e)
{
if_add_dept go = new if_add_dept();
go.Show();
}
private void addEmployeToolStripMenuItem_Click(object sender, EventArgs e)
{
if_add_employee go = new if_add_employee();
go.Show();
}
Just keep track of the last form you created in a variable:
private Form lastForm;
private void showForm(Form frm) {
frm.FormClosed += (sender, ea) => {
if (object.ReferenceEquals(lastForm, sender)) lastForm = null;
};
frm.Show();
if (lastForm != null) lastForm.Close();
lastForm = frm;
}
And use showForm() to display your forms:
private void addCampusToolStripMenuItem_Click(object sender, EventArgs e)
{
showForm(new if_add_campus());
}
Not tested, should be close.