我想知道当我点击contextMenuStrip(1项名为clear)时是否有任何方法可以清除文本框。我有4个文本框,我已经为所有文本框提供了相同的contextMenuStrip名称。在运行应用程序时,我向textbox1添加了一些文本。当我右键单击textbox1并选择clear(contextMenuStripItem)时,应清除所有文本。同样,当我右键单击textbox2并选择clear时,应清除所有文本。我在winforms VS2010编程
提前致谢:)
编辑:我尝试的代码可能没有正确的命名约定:
在Designer.cs中
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.clearToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(100, 26);
//
// textBox1
//
this.textBox1.ContextMenuStrip = this.contextMenuStrip1;
this.textBox1.Location = new System.Drawing.Point(224, 191);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 8;
//
// clearToolStripMenuItem
//
this.clearToolStripMenuItem.Name = "clearToolStripMenuItem";
this.clearToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.clearToolStripMenuItem.Text = "clear";
this.clearToolStripMenuItem.Click += new System.EventHandler(this.clearToolStripMenuItem_Click);
this.Controls.Add(this.textBox1);
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem clearToolStripMenuItem;
private System.Windows.Forms.TextBox textBox1;
在Form.cs中
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
ToolStripItem menuItem = sender as ToolStripItem;
if (menuItem != null)
{
ContextMenuStrip owner = menuItem.Owner as ContextMenuStrip;
if (owner != null)
{
Control sourceControl = owner.SourceControl;
MessageBox.Show(sourceControl.Name);
MessageBox.Show(sourceControl.Text);
}
}
}
所以当我右键单击textBox1时,它会显示其文本和名称。所以我的问题是如何清除该文本。为所有文本框设置相同的contextMenu并清除文本是否有用,或者我必须为不同的文本框使用不同的contextMenu。
答案 0 :(得分:4)
替换
Control sourceControl = owner.SourceControl;
与
TextBox sourceControl = owner.SourceControl as TextBox;
sourceControl.Text = string.Empty;
// or sourceControl.Clear();