Toolstripmenuitem点击事件

时间:2014-07-20 12:56:29

标签: c# winforms

我使用此代码将项目添加到我的菜单中:

private void oKToolStripMenuItem2_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(toolStripTextBox3.Text))
    {
        MessageBox.Show("Please enter a username in the textbox.", "Error");
        return;
    }
    var username = usernamesToolStripMenuItem1.DropDownItems.Add(toolStripTextBox3.Text);
    username.Name = toolStripTextBox3.Text;
    Properties.Settings.Default.Usernames.Add(toolStripTextBox3.Text);
    toolStripTextBox3.Clear();
}

如何制作/调用它的点击事件?目标是当您单击用户名时,它会在文本框中填充它。我希望有一个.selecteditem,但我找不到它。

3 个答案:

答案 0 :(得分:1)

您可以先创建菜单项,然后为其指定不同的事件:

    private void addNameToolStripMenuItem_Click(object sender, EventArgs e)
    {
        ...
        var newItem = new ToolStripMenuItem(toolStripTextBox3.Text);
        newItem.Click +=new EventHandler(addedItemClickEvent);
        newItem.Name = toolStripTextBox3.Text;
        usernamesToolStripMenuItem1.DropDownItems.Add(newItem);
        //Properties.Settings.Default.Usernames.Add(toolStripTextBox3.Text);
        toolStripTextBox3.Clear();
    }

然后,您可以分析发件人姓名以执行各种操作:

    private void addedItemClickEvent(object sender, EventArgs e)
    {
        MessageBox.Show((sender as ToolStripMenuItem).Text);
    }

答案 1 :(得分:0)

创建菜单项后订阅Click事件。

您可以在一行中执行此操作:

username.Click += (s, e) => SomeTextBox.Text = "test";

如果您更容易阅读,请创建一个单独的方法:

private void oKToolStripMenuItem2_Click(object sender, EventArgs e)
{
    ...
    var username = usernamesToolStripMenuItem1.DropDownItems.Add(toolStripTextBox3.Text);
    username.Click += username_Click;
    ...
}

void username_Click(object sender, EventArgs e)
{
    SomeTextBox.Text = "test";
}

答案 2 :(得分:0)

只需使用接受Add作为输入的ToolStripItem方法的重载,并使用接收委托作为输入的ToolStripLabel构造函数创建该项:

private void oKToolStripMenuItem2_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(toolStripTextBox3.Text))
    {
        MessageBox.Show("Please enter a username in the textbox.", "Error");
        return;
    }

    var username = usernamesToolStripMenuItem1.DropDownItems.Add(
                         new ToolStripLabel(toolStripTextBox3.Text, (Image) null,
                         false, toolstrip_click));

    username.Name = toolStripTextBox3.Text;
    Properties.Settings.Default.Usernames.Add(toolStripTextBox3.Text);
    toolStripTextBox3.Clear();
}

void toolstrip_click(object sender, EventArgs e)
{
    MessageBox.Show(((ToolStripLabel)sender).Text);  // Write your code here
}