开发者

C#, access (get or read) the textBox values in a static method?

I have a form (form1) that has a text field (textBox1) I have a class that has the method "public static string getValue()"

how I can read the value of the textBox1 within the method getValue() ??

here is my code

namespace MyProgram
{
    public partial class Form1: Form
    {
      ---------------------------------
      ---------------------------------
      ---------------------------------
    }
}

the other cl开发者_如何学JAVAass

namespace MyProgram
{
    class values
    {

        public static string getValues()
        {

            string v;
            v = ------get value from textBox1 in Form1
            return v;
        }

    }
}

the whol software is build in this structure, so I hope there is some standard way in C# to get these values in the method getValue()


You can not. The property is in the instance of the class, the static method has no pointer to it. Broken by design.


You have to instantiate new object of Form1 and get the value. Or else add a delegate in form1 and call it from getValue, such that the return value of delegate should be the textbox value.


You can instantiate, show, and dispose of the form inside the static method. An example:

public static string GetValues()
{
    string value = null;

    using (var form = new Form1())
    {
        DialogResult result = form.ShowDialog();

        if (result == DialogResult.OK)
        {
            value = form.textBox1.Text;
        }
    }

    return value;
}

The using block takes care of freeing the resources allocated for the form. ShowDialog shows the form as a modal dialog.

While this works for simple dialog boxes, it is probably not what you want to do in every case. The method will block the current thread until the user closes the form. Look at other applications and sample code. As @Dan Abramov wrote, Reconsider your design.


foreach(Control c in Form1.Controls) {
     if(c.getType() == TextBox) {
            TextBox tb = (TextBox)c; 
            string value = tb.Text;
     }

}

But why don't you just read the value from the form?

Textbox1.Text

Consider the KISS-principle!


With few assumptions - you can use this code snippet

private static void GetValue(object sender, TransferEventArgs e)
{

  Application.OpenForms["FormSomeForm"].Controls["textBoxSomeTextbox"].Text = @"Some Value";

}

Depend on your other code it is also helpful to define the control / variable "public" as for example:

public System.Windows.Forms.TextBox textBoxSomeTextbox;

... or use the VS Studio GUI - Properties:

C#, access (get or read) the textBox values in a static method?

Tested; VS 2019 - NET 4.8 - 1/29/2022

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜