Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Tool Bars and Menus

Status
Not open for further replies.

kimmer7389

Technical User
Nov 27, 2001
95
US
I am new to windows applications and C# both so please don't be to hard on me.

I am designing a Windows application using C#.
The main form has a file menu and a tool bar.
I can open other forms from my file menu without any problems.

I want to open forms from my tool bar using the same method as I open forms from the file menu using the tag property.

I am using Visual Studio and my File Menu and my Tool Bar are already created.

This is one example of how I am opening a form from the file menu

private void newMenuItem_Click(object sender, System.EventArgs e)
{


// TODO - set AddEditProjection properties, probably a data row
if (AddEditProjection.ShowDialog()
== DialogResult.OK)
{

}
else
{

}
AddEditProjection.Hide();

I am trying to use this code on the ToolBarButton Click Event

private void toolBarButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
ToolBarButton anyButton = e.Button;
MenuItem anyMenuItem = (MenuItem)
anyButton.Tag;
anyMenuItem.PerformClick();
}

After the InitializeComponent method I have this

public mainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
ToolBarButton openButton = new
ToolBarButton();
addButton.Tag = newMenuItem;

Any help with what I am doing wrong would be greatly appreciated. Using this code produces an error message. The application builds but when I click on the button I get the following error message:

An unhandled exception of type 'System.InvalidCastException' occurred in FHP Client.exe

Additional information: Specified cast is not valid.
 
The code in toolBarButtonClick() is Okay.
I think you get that error because one ToolBarButton has no Tag proprty set and in this case is null.
Code:
toolBarButton2.Text = "Open";
toolBarButton2.Tag = menuItem2;
toolBarButton3.Text = "Save"; // missing Tag for button3
toolBarButton4.Tag = menuItem4;
To find out which one has no Tag set change the function like here:
Code:
protected void toolBar1_ButtonClick (	Object sender, ToolBarButtonClickEventArgs e)
{
	ToolBarButton anyButton = e.Button;
	MenuItem anyMenuItem = (MenuItem)anyButton.Tag;
	if (anyMenuItem!=null)
		anyMenuItem.PerformClick();
	else
	System.Windows.Forms.MessageBox.Show("ToolBarButton without tag: " + anyButton.Text);
}
-obislavu-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top