Hans Ajani Hans Ajani - 2 months ago 15x
ASP.NET (C#) Question

SQL Query from c# class

I'm trying to modify my code by placing the sql connections and querys into a c# class because currently all my .aspx.cs has connection strings with different types of querys with parameters

Like this:

string CS2 = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con2 = new SqlConnection(CS2))
SqlCommand cmd2 = new SqlCommand("SELECT nombre FROM [Portal_B2e].[dbo].[usuarios] WHERE numero_personal = " + lblCedula.Text + "", con2);
object labels = cmd2.ExecuteScalar();
lblNombre.Text = labels.ToString();

As you notice i complete the query with "lblCedula.Text" so when i try to do this from a c# class it says lblCedula does not exist in this content.

How could i make a reference to the label i have in another page from the class?

This is my code in the c# class

public static List<Perfil> DeletePerfil()
List<Perfil> listDelete = new List<Perfil>();

string CS = ConfigurationManager.ConnectionStrings["DBCSATE"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
SqlCommand cmd = new SqlCommand("SELECT nombre FROM [Portal_B2e].[dbo].[usuarios] WHERE numero_personal = " + lblCedula.Text + "", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
Perfil perfil1 = new Perfil();
perfil1.perfil = Convert.ToInt32(rdr["perfil"]);
perfil1.descripcion = rdr["descripcion"].ToString();

return listDelete;


Like others have said, pass in lblCedula.Text as a string parameter to your DeletePerfil method:

public static List<Perfil> DeletePerfil(string numeroPersonal)

Then your call looks like this:

var deletedProfiles = YourClass.DeletePerfil(lblCedula.Text);

And like sstan's comment mentioned, make sure you use SQLParameters instead of using string concatenation to avoid a SQL Injection security hole.