Usuário com melhor resposta
Tratar eventos de Controles

Pergunta
-
Respostas
-
Voce pode criar os delagates em uma classe à parte (nao recomendo).
Um form no VS é uma classe parcial. A parte que voce vê contem o seu código. A outra contem as informaçoes de desiner.
Se voce colocar os eventos fora, voce perde a integraçao com a IDE
Veja um formulario simples contendo um botao e um textbox fica assim:
form1.designer.cs
namespace WindowsFormsApplication2 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private 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> private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(28, 38); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(221, 20); this.textBox1.TabIndex = 0; // // button1 // this.button1.Location = new System.Drawing.Point(132, 79); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(116, 42); this.button1.TabIndex = 1; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 262); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button1; } }
form1.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(textBox1.Text); } } }
Note que o delegate do evento click fica dentro da classe form1, mas no arquivo form1.cs e o codigo que liga o evento do objeto button1 ao delegate fica tambem dentro da classe form1 mas no arquivo form1.designer.cs
Isso é feito porque toda a vez que voce adiciona um controle ou modifica as posiçoes deles a IDE do VS modificia o arquivo .desiner.cs sem interferir no codigo que voce escreveu.
Voce tem que ver tudo como uma grande classe.
Agora para que voce ligue os eventos à uma classe externa, ai a coisa complica um pouco (lembrando que é possivel). Olhe a salada que fica:
Vou criar o evento click do button1 em uma classe externa chamada eventos, entao o codigo fica assim:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication2 { class Eventos { public void button1_Click(object sender, EventArgs e) { MessageBox.Show(((Form1)((Button)sender).Parent).textBox1.Text); } } }
Agora eu tenho que modificar manualmente o designer.cs para ligar o codigo à essa classe:
namespace WindowsFormsApplication2 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private 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> private void InitializeComponent() { Eventos evt = new Eventos();//Instancia um objeto Eventos this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(28, 38); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(221, 20); this.textBox1.TabIndex = 0; // // button1 // this.button1.Location = new System.Drawing.Point(132, 79); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(116, 42); this.button1.TabIndex = 1; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(evt.button1_Click);//liga o evento do botao ao delegate // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 262); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion public System.Windows.Forms.TextBox textBox1;// variavies privadas tornadas publicas para ter acesso externo public System.Windows.Forms.Button button1; } }
Pode ter certeza que fica pior.
William John Adam Trindade
Analyste-programmeur
Sogi Informatique ltée
If you found this post helpful, please "Vote as Helpful". If it actually answered your question, remember to "Mark as Answer". Se achou este post útil, por favor clique em "Votar como útil". Se por acaso respondeu sua dúvida, lembre de "Marcar como Resposta".- Sugerido como Resposta Mariano1776 segunda-feira, 19 de fevereiro de 2018 22:22
- Marcado como Resposta Jonh Kalak terça-feira, 20 de fevereiro de 2018 00:01
Todas as Respostas
-
Voce pode criar os delagates em uma classe à parte (nao recomendo).
Um form no VS é uma classe parcial. A parte que voce vê contem o seu código. A outra contem as informaçoes de desiner.
Se voce colocar os eventos fora, voce perde a integraçao com a IDE
Veja um formulario simples contendo um botao e um textbox fica assim:
form1.designer.cs
namespace WindowsFormsApplication2 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private 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> private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(28, 38); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(221, 20); this.textBox1.TabIndex = 0; // // button1 // this.button1.Location = new System.Drawing.Point(132, 79); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(116, 42); this.button1.TabIndex = 1; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 262); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button1; } }
form1.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(textBox1.Text); } } }
Note que o delegate do evento click fica dentro da classe form1, mas no arquivo form1.cs e o codigo que liga o evento do objeto button1 ao delegate fica tambem dentro da classe form1 mas no arquivo form1.designer.cs
Isso é feito porque toda a vez que voce adiciona um controle ou modifica as posiçoes deles a IDE do VS modificia o arquivo .desiner.cs sem interferir no codigo que voce escreveu.
Voce tem que ver tudo como uma grande classe.
Agora para que voce ligue os eventos à uma classe externa, ai a coisa complica um pouco (lembrando que é possivel). Olhe a salada que fica:
Vou criar o evento click do button1 em uma classe externa chamada eventos, entao o codigo fica assim:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication2 { class Eventos { public void button1_Click(object sender, EventArgs e) { MessageBox.Show(((Form1)((Button)sender).Parent).textBox1.Text); } } }
Agora eu tenho que modificar manualmente o designer.cs para ligar o codigo à essa classe:
namespace WindowsFormsApplication2 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private 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> private void InitializeComponent() { Eventos evt = new Eventos();//Instancia um objeto Eventos this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(28, 38); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(221, 20); this.textBox1.TabIndex = 0; // // button1 // this.button1.Location = new System.Drawing.Point(132, 79); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(116, 42); this.button1.TabIndex = 1; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(evt.button1_Click);//liga o evento do botao ao delegate // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 262); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion public System.Windows.Forms.TextBox textBox1;// variavies privadas tornadas publicas para ter acesso externo public System.Windows.Forms.Button button1; } }
Pode ter certeza que fica pior.
William John Adam Trindade
Analyste-programmeur
Sogi Informatique ltée
If you found this post helpful, please "Vote as Helpful". If it actually answered your question, remember to "Mark as Answer". Se achou este post útil, por favor clique em "Votar como útil". Se por acaso respondeu sua dúvida, lembre de "Marcar como Resposta".- Sugerido como Resposta Mariano1776 segunda-feira, 19 de fevereiro de 2018 22:22
- Marcado como Resposta Jonh Kalak terça-feira, 20 de fevereiro de 2018 00:01
-