简体   繁体   中英

How do I get text from the textbox into Button event in c#

I have created this code

created form in .dll file and added controles

        TextBox dbname = new TextBox();  
        dbname.BorderStyle = BorderStyle.Fixed3D;
        dbname.Location = new Point(236, 81);

        Button Create = new Button();
        Create.FlatStyle = FlatStyle.Flat;
        Create.FlatAppearance.BorderSize = 0;
        Create.Location = new Point(261, 115);
        Create.Text = "Create";
        Create.Click += new System.EventHandler(this.Create_Click);

How do I get text from the text box?

private void Create_Click(object sender , EventArgs e)
    {

        SaveFileDialog _sfd_ = new SaveFileDialog();

        _sfd_.Filter = "Housam Printing |*.HP";
        _sfd_.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
        _sfd_.FileName = dbname.text;
        _sfd_.Title = "Database location";
    }

In order to make your controls accessible to the rest of your class, you need to define them at the class level. Then you can initialize them in the constructor or the Form_Load event (or wherever you want), and can access them from other class methods:

public partial class Form1 : Form
{
    // Declare your controls at the class level so all methods can access them
    private TextBox dbName;
    private Button create;

    private void Form1_Load(object sender, EventArgs e)
    {
        dbName = new TextBox
        {
            BorderStyle = BorderStyle.Fixed3D,
            Location = new Point(236, 81)
        };
        Controls.Add(dbName);

        create = new Button
        {
            FlatStyle = FlatStyle.Flat,
            Location = new Point(261, 115),
            Text = "Create",
        };
        create.FlatAppearance.BorderSize = 0;
        create.Click += create_Click;
        Controls.Add(create);
    }

    private void create_Click(object sender , EventArgs e)
    {
        var sfd = new SaveFileDialog
        {
            Filter = "Housam Printing |*.HP",
            InitialDirectory = AppDomain.CurrentDomain.BaseDirectory,
            FileName = dbName.Text,
            Title = "Database location"
        };
    }
}        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM