Sunday, August 29, 2010

Handling event from Context Menu strip after a Right Click

Recently I deal with this problems for 1-1.5 hours. Anyway, lastly I figured it out how to perform this operations: Here are the steps. We need three controls for this

  • Windows form

  • ListView Control

  • ContextMenu Strip


Step-1:Loading listview items::



The following code loads the items to listview control.

protected void load_courses()
{

//code for loading the courses
try {
OleDbConnection conn = new OleDbConnection(StaticData.connection_string);
conn.Open();
string select_courses = "select * from Course";
OleDbDataAdapter oda = new OleDbDataAdapter(select_courses, conn);
DataTable dt = new DataTable();
oda.Fill(dt);

//databinding to the listview
TestlistView.Items.Clear();
for(int i=0;i < dt.Rows.Count;i++)
{
DataRow row = dt.Rows[i];
ListViewItem lvi = new ListViewItem(row["CourseNo"].ToString());
lvi.SubItems.Add(row["CourseID"].ToString());
lvi.SubItems.Add(row["Credit"].ToString());
TestlistView.Items.Add(lvi);
}


}
catch (Exception exc) { }
}



private void Form1_Load(object sender, EventArgs e)
{

//code for loading the courses
load_courses();

}



Step-2:Handling the right click event on listview items:



private void TestlistView_MouseClick(object sender, MouseEventArgs e)
{

if (e.Button == MouseButtons.Right)
{
Point pt = TestlistView.PointToScreen(e.Location);
contextMenuStrip1.Show(pt);
}


}


Step-3:Handling context menu strip event



private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Text == "Upload")
{
MessageBox.Show("Upload started for:" + TestlistView.SelectedItems[0].Text);
}
}




Thats how we can use right click event to show a context menu strip and handle menu strip click events.
thanks. Masud(29-08-2010)