Résultat select dans un formulaire en C#

aminaxy Messages postés 151 Date d'inscription jeudi 1 septembre 2011 Statut Membre Dernière intervention 18 août 2016 - 14 juin 2014 à 23:11
aminaxy Messages postés 151 Date d'inscription jeudi 1 septembre 2011 Statut Membre Dernière intervention 18 août 2016 - 16 juin 2014 à 16:42
Bonsoir,
j'ai un formulaire qui contient 2 listes Box et 2 TextBox,je doit afficher dans ce formulaire des données à partir d'une base de données,voici mon code,mais si vous pouvez l'améliorer car je pense que je répète toujours les mêmes instructions:

public Form3(Form10 f10)
{
// TODO: Complete member initialization
InitializeComponent();
this.form10 = f10;
if (form10.fichierDataGridView1.RowCount > 0) // controle si le dataGrid n'est pas vide
{
sel1 = (string)form10.fichierDataGridView1.CurrentRow.Cells[0].Value;
sel2 = (string)form10.fichierDataGridView1.CurrentRow.Cells[1].Value;
textBox1.Text = sel1;
textBox2.Text = sel2;
SqlConnection connection1 = new SqlConnection(connectionString);
SqlConnection connection2 = new SqlConnection(connectionString);
SqlConnection connection3 = new SqlConnection(connectionString);
SqlConnection connection4 = new SqlConnection(connectionString);
connection1.Open();
req1 = "select capital from fichier where code='"+textBox1.Text+"';"; //numero_cpte,intitulé_cpte from compte where numero_cpte=cast(" + a + " as int); "; //OR intitulé_cpte like '%" + b + "%' OR type_cpte='" + c + "' OR index_full_text_cpte like'%" + d + "%';";
SqlCommand sql1 = new SqlCommand(req1, connection1);
SqlDataReader dre = sql1.ExecuteReader();
if (dre.Read())
{
textBox4.Text = dre.GetValue(0).ToString();
}
connection1.Close();

connection2.Open();
req2 = "select form_juri from fichier where code='" + textBox1.Text + "';";
SqlCommand sql2 = new SqlCommand(req2, connection2);
SqlDataReader dre2 = sql2.ExecuteReader();
if (dre2.Read())
{
listBox1.Text = dre2.GetValue(0).ToString();
}
connection2.Close();

connection3.Open();
req3 = "select activi from fichier where code='" + textBox1.Text + "';";
SqlCommand sql3 = new SqlCommand(req3, connection3);
SqlDataReader dre3 = sql3.ExecuteReader();
if (dre3.Read())
{
textBox3.Text = dre3.GetValue(0).ToString();
}
connection3.Close();

connection4.Open();

req4 = "select filiale from fichier where code='" + textBox1.Text + "';";
SqlCommand sql4 = new SqlCommand(req4, connection4);
SqlDataReader dre4 = sql4.ExecuteReader();
if (dre4.Read())
{
listBox2.Text = dre4.GetValue(0).ToString();
}
connection4.Close();
//int o = sql1.ExecuteNonQuery();
//MessageBox.Show(o + " succès");
textBox1.Enabled = false;
}

}


merci pour l'aide :)

2 réponses

Whismeril Messages postés 19025 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 19 avril 2024 656
14 juin 2014 à 23:43
2
yann_lo_san Messages postés 1137 Date d'inscription lundi 17 novembre 2003 Statut Membre Dernière intervention 23 janvier 2016 26
15 juin 2014 à 15:16
Salut,

attention, avec ce genre de code on peut facilement faire de l'injection SQL et saturer ton serveur.

req1 = "select capital from fichier where code='"+textBox1.Text+"';";

Imagines que j'ai saisi ceci dans le textBox1 : ' or 1=1 --
tu peux faire le test toi-même. (ce texte ferme la chaine SQL et rajoute une expression qui rend vrai puis met tous le reste en commentaire SQL)


Sinon pour ton problème de répétition,
- une petite fonction allègerait grandement ton code
- Utilisation de la fonction ExecuteScalar() à la place du Reader
- Utilisation des SqlParameter pour éviter l'injection SQL
- Placer la connexion en tant qu'instance permet de ne l'ouvrir et fermer qu'une seule fois
- Optimiser la déclaration d'objet multiples (string req1, req12, req3, req4) ect...

class Form3
{
	const string connectionString = "laChaineDeConnexion";
	// Place la connexion en tant qu'instance (ouverte et fermée une seule fois)
	SqlConnection _conn = new SqlConnection(connectionString);

	public Form3()
	{
                textbox1.Text = (string)form10.fichierDataGridView1.CurrentRow.Cells[0].Value;
                textbox2.Text = (string)form10.fichierDataGridView1.CurrentRow.Cells[1].Value;

		_conn.Open();

		string req = "select capital from fichier where code = @p";
		textBox4.Text = (GetRecordsetValue(req, textBox1.Text) as String);
		
		req = "select form_juri from fichier where code = @p";
		listBox1.Text = (GetRecordsetValue(req, textBox1.Text) as String);

		req = "select activi from fichier where code = @p";
		textBox3.Text = (GetRecordsetValue(req, textBox1.Text) as String);

		req = "select filiale from fichier where code = @p";
		listBox2.Text = (GetRecordsetValue(req, textBox1.Text) as String);

		// ATTENTION: Aucune gestion d'erreur (try/catch)
		_conn.Close();
	}


	// Méthode à adapter si plusieurs paramètres 
	// (HashTable par exemple avec nomParam en clef et ValParam en valeur
	private Object GetRecordsetValue(string req, string sValParam)
	{
		// ExecuteScalar est optimisée pour récupérer une seule valeur
		SqlCommand cmd = null;
		try
		{
			cmd = new SqlCommand(req, _conn);
			cmd.Parameters.AddWithValue("@p", sValParam);
			return cmd.ExecuteScalar();
		}
		catch 
		{
			// ATTENTION: Aucune gestion d'erreur
			return String.Empty;
		}
		finally
		{
			cmd.Dispose();
		}
	}
}


Bye ...
2
aminaxy Messages postés 151 Date d'inscription jeudi 1 septembre 2011 Statut Membre Dernière intervention 18 août 2016
16 juin 2014 à 16:42
merci yann_lo_san
0
Rejoignez-nous