C# 问题:如何从另一个表单操作一个表单上的文本框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/510497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# issue: How do I manipulate a Textbox on one form from another form?
提问by OneShot
I'm trying to create my own error window for the project I am working on. When I show my error window I have no way to pass the error message, and user message to the Error window because the "ErrorMessage.Text" cannot be seen in the classes I make.
我正在尝试为我正在处理的项目创建自己的错误窗口。当我显示我的错误窗口时,我无法将错误消息和用户消息传递到错误窗口,因为在我创建的类中看不到“ErrorMessage.Text”。
I went into the form designer generated code and tried to make the TextBox static, but that just breaks things. Can I make a TextBox public / static so I can change it from another form?
我进入表单设计器生成的代码并尝试使 TextBox 成为静态,但这只会破坏事情。我可以将 TextBox 设为 public/static 以便我可以从其他表单更改它吗?
- How do I make a TextBox Static Public so I can manipulate it across other forms, or is there another method for doing this?
- 如何使 TextBox 静态公共,以便我可以跨其他表单操作它,或者是否有其他方法可以做到这一点?
EDIT:
编辑:
Okay, for more information...
好的,了解更多信息...
I have my own Form created. It is called "formErrorWindow." I need to display the form that i've pre-designed with the message set from another form. The only way I can do this is if I create a Function in the windows designer area for the form, and I set the variables with "this.errorMsg.text = error." The only way I can see that function is if I set it to static. If I set the function to Static, when I try and put "this.errorMsg.Text = error" I get this error: An object reference is required for the non-static field, method, or property.
我创建了自己的表单。它被称为“formErrorWindow”。我需要显示我用另一个表单中的消息集预先设计的表单。我能做到这一点的唯一方法是在窗体的 Windows 设计器区域中创建一个函数,并使用“this.errorMsg.text = error”设置变量。我可以看到该功能的唯一方法是将其设置为静态。如果我将函数设置为静态,当我尝试输入“this.errorMsg.Text = error”时,我会收到此错误:非静态字段、方法或属性需要对象引用。
Here is what I've attempted:
这是我尝试过的:
namespace LCR_ShepherdStaffupdater_1._0
{
partial class formErrorWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
public System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
///
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
// ********* HERE IS THE FUNCTION THAT IVE ADDED BELOW. THIS WOULD WORK BUT.... *********
public static void showError(string errorTitle, string usrMsg, string errorMsg)
{
formErrorWindow errorWindow = new formErrorWindow();
errorMsgItem.Text = errorMsg;
errorTitleItem.Text = "Error! : " + errorTitle;
usrMsgItem.Text = usrMsg;
errorWindow.ShowDialog();
}
// ********* HERE IS THE FUNCTION THAT IVE ADDED ABOVE. THIS WOULD WORK BUT.... *********
// ********* I get an error: "An object reference is required for the non-static field, method, or property." *********
public void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(formErrorWindow));
this.usrMsgItem = new System.Windows.Forms.TextBox();
this.errorTitleItem = new System.Windows.Forms.Label();
this.errorMsgItem = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.label2 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// usrMsgItem
//
this.usrMsgItem.Enabled = false;
this.usrMsgItem.Location = new System.Drawing.Point(13, 37);
this.usrMsgItem.Multiline = true;
this.usrMsgItem.Name = "usrMsgItem";
this.usrMsgItem.Size = new System.Drawing.Size(334, 81);
this.usrMsgItem.TabIndex = 0;
this.usrMsgItem.Text = "Undefined";
//
// errorTitleItem
//
this.errorTitleItem.AutoSize = true;
this.errorTitleItem.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.errorTitleItem.ForeColor = System.Drawing.Color.Red;
this.errorTitleItem.Location = new System.Drawing.Point(12, 9);
this.errorTitleItem.Name = "errorTitleItem";
this.errorTitleItem.Size = new System.Drawing.Size(152, 20);
this.errorTitleItem.TabIndex = 1;
this.errorTitleItem.Text = "Error! : Undefined";
//
// errorMsgItem
//
this.errorMsgItem.Enabled = false;
this.errorMsgItem.Location = new System.Drawing.Point(0, 21);
this.errorMsgItem.Multiline = true;
this.errorMsgItem.Name = "errorMsgItem";
this.errorMsgItem.Size = new System.Drawing.Size(329, 101);
this.errorMsgItem.TabIndex = 2;
this.errorMsgItem.Text = "Undefined";
//
// button1
//
this.button1.Location = new System.Drawing.Point(272, 256);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 3;
this.button1.Text = "Continue";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.errorMsgItem);
this.panel1.Location = new System.Drawing.Point(12, 124);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(335, 126);
this.panel1.TabIndex = 4;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(68, 1);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(189, 17);
this.label2.TabIndex = 3;
this.label2.Text = "Technical Error Message";
//
// formErrorWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.ClientSize = new System.Drawing.Size(359, 290);
this.Controls.Add(this.panel1);
this.Controls.Add(this.button1);
this.Controls.Add(this.errorTitleItem);
this.Controls.Add(this.usrMsgItem);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "formErrorWindow";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Error!";
this.VisibleChanged += new System.EventHandler(this.formErrorWindow_VisibleChanged);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label2;
public System.Windows.Forms.TextBox usrMsgItem;
public System.Windows.Forms.Label errorTitleItem;
public System.Windows.Forms.TextBox errorMsgItem;
}
}
Look for the function I've added above. How do I get that to compile and do what I want it to do WITHOUT that error I keep getting: An object reference is required for the non-static field, method, or property.
查找我在上面添加的函数。我如何让它编译并执行我想要它做的事情而没有我不断收到的错误:非静态字段、方法或属性需要对象引用。
采纳答案by Ric Tokyo
Yes! have a function made public that can receive this text:
是的!有一个可以接收此文本的公开函数:
pseudo: public void updateTextBox(string new_text)
and have the function update the textbox from there.
并让函数从那里更新文本框。
don't mix UI with logic.
不要将 UI 与逻辑混为一谈。
回答by Peter
You can make the TextBox public first of. Second make a static form(name of your form) variable and put the form there each time its loaded... This is not a good solution in my eyes but without knowing more about your design its the best i can come up with...
您可以首先将 TextBox 设为公开。其次制作一个静态表单(您的表单名称)变量,并在每次加载时将表单放在那里......这在我看来不是一个好的解决方案,但没有更多地了解您的设计,这是我能想到的最好的...... .
回答by Gerrie Schenck
I would just pass the message as a constructor parameter.
我只是将消息作为构造函数参数传递。
MyMessageBox messageBox = new MyMessageBox("My error message");
messageBox.Show();
回答by Frederick The Fool
Allowing public access to an object contained in your class may be a design. How about writing a property in the error window class called ErrorText
and inside that property set the ErrorMessage.Text
to the passed string? Or am I missing something?
允许公开访问您的类中包含的对象可能是一种设计。如何在调用的错误窗口类中编写一个属性ErrorText
并将该属性设置ErrorMessage.Text
为传递的字符串?或者我错过了什么?
回答by Ric Tokyo
If you really want to go with accessing the controls directly:
如果您真的想直接访问控件:
public Form2(Form1 form1)
{
InitializeComponent();
Owner = form1;
_form1 = form1;
}
now you can access the controls on form1 this way:
现在您可以通过以下方式访问 form1 上的控件:
_form1.theForm1ControlName
回答by Ric Tokyo
You could create a method in the Error window's class which could be something like:
您可以在错误窗口的类中创建一个方法,它可能是这样的:
public void SetErrorText(string errorText)
{
this.ErrorMessage.Text = errorText; // assuming the TextBox' ID is ErrorMessage.
}
回答by Brandon
Sounds like you're on the right track by adding the public function you did, but you shouldn't have to make it static. As a general rule, if you have to go into the Designer Generated Code, something isn't right, so let's get out of there - it doesn't mean you can't add code to the form, obviously, but don't do it in that section :)
通过添加您所做的公共功能,听起来您走在正确的轨道上,但您不应该让它保持静态。作为一般规则,如果您必须进入设计器生成的代码,有些事情是不对的,所以让我们离开那里 - 显然,这并不意味着您不能向表单添加代码,但不要在那个部分做:)
The error you're getting I believe originates from having a non-instantiated object (i.e. creating the error form like:
你得到的错误我相信源于有一个非实例化的对象(即创建错误形式,如:
formErrorWindow myErrorWindow;
as opposed to instantiating it / creating an instance of it like so:
而不是像这样实例化它/创建它的实例:
formErrorWindow myErrorWindow = new formErrorWindow();
You've made the function static, so you can see it from anywhere, however that function can't actually do anything because the form that it runs on doesn't exist yet until you use " = new formErrorWindow();".
您已将函数设为静态,因此您可以从任何地方看到它,但是该函数实际上无法执行任何操作,因为在您使用“= new formErrorWindow();”之前,它运行的表单尚不存在。
So if I'm in a form called "MainForm" and I want to show an error, using the name of the function you provided it would be done like this:
因此,如果我在一个名为“MainForm”的表单中,并且我想显示一个错误,则使用您提供的函数名称将如下完成:
formErrorWindow myErrorWindow = new formErrorWindow();
myErrorWindow.showError("Title", "User Message Here", "Error Message Here");
myErrorWindow.ShowDialog();
The key is to make sure nothing is static and then make sure you're initializing the formErrorWindow with = new formErrorWindow();
关键是要确保没有任何东西是静态的,然后确保使用 = new formErrorWindow(); 初始化 formErrorWindow;
回答by auraham
public partial class Form1 : Form
{
private static TextBox box;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// box
box = new TextBox();
box.Location = new System.Drawing.Point(87, 230);
box.Name = "box";
box.Size = new System.Drawing.Size(100, 20);
box.TabIndex = 1;
this.Controls.Add(box);
}
}
回答by Justin W
Pass the TextBox to the function/method like so
像这样将 TextBox 传递给函数/方法
public static void myFunc(TextBox textBox1)
{
textBox1.Text = "do stuff";
{