octobre
2005
Je vais montrer comment récupérer simplement des informations d’un formulaire à l’autre. Ces quelques lignes ne s’adressent pas aux personnes expérimentées mais simplement aux personnes qui debutent sur .NET.
J’ai décidé d’écrire ceci car depuis 2 semaines j’ai plusieurs fois expliqué ces choses à divers personnes sur le forum .NET. Alors comme ca, la prochaine fois je donnerai le lien directement.
Pour récupérer des informations d’un formulaire à l’autre il y a 2 cas :
– Nous avons une référence sur le formulaire qui contient les informations voulues
– Nous n’avons pas de référence sur le formulaire qui contient nos informations
Nous allons partir d’un cas très simple ou l’utilisateur va saisir une information dans un textbox sur un formulaire.
1. Récupérer des informations depuis un formulaire dont nous avons la référence
Ce premier est cas est très simple. C’est le cas ou vous lancez un second formulaire depuis le premier en demandant à l’utilisateur de saisir les informations que vous avez besoin.
Exemple :
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace GetInfoFromForm
{
/// <summary>
/// Description résumée de Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox txtInfo;
private System.Windows.Forms.Button btnNextForm;
/// <summary>
/// Variable nécessaire au concepteur.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Requis pour la prise en charge du Concepteur Windows Forms
//
InitializeComponent();
//
// TODO : ajoutez le code du constructeur après l'appel à InitializeComponent
//
}
/// <summary>
/// Nettoyage des ressources utilisées.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Code généré par le Concepteur Windows Form
/// <summary>
/// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
/// le contenu de cette méthode avec l'éditeur de code.
/// </summary>
private void InitializeComponent()
{
this.txtInfo = new System.Windows.Forms.TextBox();
this.btnNextForm = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// txtInfo
//
this.txtInfo.Location = new System.Drawing.Point(16, 16);
this.txtInfo.Name = "txtInfo";
this.txtInfo.ReadOnly = true;
this.txtInfo.Size = new System.Drawing.Size(160, 20);
this.txtInfo.TabIndex = 0;
this.txtInfo.Text = "";
//
// btnNextForm
//
this.btnNextForm.Location = new System.Drawing.Point(184, 16);
this.btnNextForm.Name = "btnNextForm";
this.btnNextForm.Size = new System.Drawing.Size(96, 23);
this.btnNextForm.TabIndex = 1;
this.btnNextForm.Text = "Load Next Form";
this.btnNextForm.Click += new System.EventHandler(this.btnNextForm_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 61);
this.Controls.Add(this.btnNextForm);
this.Controls.Add(this.txtInfo);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// Point d'entrée principal de l'application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnNextForm_Click(object sender, System.EventArgs e)
{
Form2 aForm = new Form2();
aForm.ShowDialog();
txtInfo.Text = aForm.GetFirstName() + " " + aForm.GetLastName();
}
}
}
Lors du clique sur le bouton nous lancons le second formulaire.
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace GetInfoFromForm
{
/// <summary>
/// Description résumée de Form2.
/// </summary>
public class Form2 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox txtNom;
private System.Windows.Forms.TextBox txtPrenom;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button btnValider;
/// <summary>
/// Variable nécessaire au concepteur.
/// </summary>
private System.ComponentModel.Container components = null;
private string myFirstName = null;
private string myLastName = null;
public Form2()
{
//
// Requis pour la prise en charge du Concepteur Windows Forms
//
InitializeComponent();
//
// TODO : ajoutez le code du constructeur après l'appel à InitializeComponent
//
}
/// <summary>
/// Nettoyage des ressources utilisées.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Code généré par le Concepteur Windows Form
/// <summary>
/// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
/// le contenu de cette méthode avec l'éditeur de code.
/// </summary>
private void InitializeComponent()
{
this.txtNom = new System.Windows.Forms.TextBox();
this.txtPrenom = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.btnValider = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// txtNom
//
this.txtNom.Location = new System.Drawing.Point(112, 16);
this.txtNom.Name = "txtNom";
this.txtNom.Size = new System.Drawing.Size(160, 20);
this.txtNom.TabIndex = 0;
this.txtNom.Text = "";
//
// txtPrenom
//
this.txtPrenom.Location = new System.Drawing.Point(112, 56);
this.txtPrenom.Name = "txtPrenom";
this.txtPrenom.Size = new System.Drawing.Size(160, 20);
this.txtPrenom.TabIndex = 1;
this.txtPrenom.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 16);
this.label1.Name = "label1";
this.label1.TabIndex = 2;
this.label1.Text = "Nom";
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 56);
this.label2.Name = "label2";
this.label2.TabIndex = 3;
this.label2.Text = "Prenom";
//
// btnValider
//
this.btnValider.Location = new System.Drawing.Point(104, 96);
this.btnValider.Name = "btnValider";
this.btnValider.TabIndex = 4;
this.btnValider.Text = "Valider";
this.btnValider.Click += new System.EventHandler(this.btnValider_Click);
//
// Form2
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 133);
this.Controls.Add(this.btnValider);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtPrenom);
this.Controls.Add(this.txtNom);
this.Name = "Form2";
this.Text = "Form2";
this.ResumeLayout(false);
}
#endregion
private void btnValider_Click(object sender, System.EventArgs e)
{
myFirstName = txtNom.Text;
myLastName = txtPrenom.Text;
Close();
}
public string GetFirstName()
{
return myFirstName;
}
public string GetLastName()
{
return myLastName;
}
}
}
Ici la particularité qui nous interesse est la presence de 2 variables de classe et de 2 accesseurs qui sont :
private string myLastName = null;
public string GetFirstName()
{
return myFirstName;
}
public string GetLastName()
{
return myLastName;
}
Ces 2 variables vont contenir les données de l’utilisateur et les 2 accesseurs vont permettre de les recuperer depuis le premier form grace au code suivant :
Remplir les variables dans le Form2 :
myLastName = txtPrenom.Text;
Recuperer les varaibles dans le Form1 :
aForm.ShowDialog();
txtInfo.Text = aForm.GetFirstName() + " " + aForm.GetLastName();
Résultat :
Voila c’etait pas très difficile.
2. Récupérer des informations depuis un formulaire dont nous n’avons pas la référence
Dans ce cas de figure, il faut simplement rajouter une classe avec des attributs et des accesseurs static. Nous appelerons cette classe AppContextUtility.
Elle va ressembler à ceci :
{
private static string myFirstName = null;
private static string myLastName = null;
public static string GetFirstName()
{
return myFirstName;
}
public static void SetFirstName(string theFirstName)
{
myFirstName = theFirstName;
}
public static string GetLastName()
{
return myLastName;
}
public static void SetLastName(string theLastName)
{
myLastName = theLastName;
}
}
Ici nous allons remplacer le code de la methode btnValider_Click du Form2 par ceci :
{
AppContextUtility.SetFirstName(txtNom.Text);
AppContextUtility.SetLastName(txtPrenom.Text);
Close();
}
Ensuite il suffit d’appeler les accesseurs GetFirstName() et GetLastName() depuis n’importe quelle classe de votre application.
Donc le code du Form1 devient :
Cette maniere de faire permet de paratger des informations entre formulaires qui n’ont pas forcement de lien direct.
Voila j’ai fini, j’espere que se sera utile pour certains.
@+