how to show data in labels in c#

1k views Asked by At

I have two layers, a data layer which gets the results from the database and a UI layer which will show the data in label controls Here is the code of data layer

public class Test_DAL
{
    public DataSet getEMP(string name1)
    {

        string conn = System.IO.File.ReadAllText("Connect.txt");
        //string conn="Data Source=.\\sqlexpress;Initial Catalog=pss;Integrated Security=True";
        //string conn = ConfigurationManager.ConnectionStrings["constr"].ToString();
        SqlConnection dbconn = new SqlConnection(conn);
        dbconn.Open();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = new SqlCommand("select * from pss where Emp_code='"+name1+"'", dbconn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        dbconn.Close();
        return ds;
    }

}

And it is the code of the UI layer

    private void btn_search_Click(object sender, EventArgs e)
    {

        string empcode=txt_empcode.Text;
        Test_DAL obj1= new Test_DAL();
        obj1.getEMP(empcode);
        //dg.DataSource = obj1.getEMP(empcode).Tables[0];


    }

And my question is how to show data on labels

Thanks a lot in advance

2

There are 2 answers

0
Ehsan On

Your requirement is not very clear. Just to give you an idea of how you can do is

private void btn_search_Click(object sender, EventArgs e)
    {

        string empcode=txt_empcode.Text;
        Test_DAL obj1= new Test_DAL();
        DataSet ds = obj1.getEMP(empcode);
        //displays the data of row 1 column 1 of table 1
        yourLabel.Text  = ds.Tables[0].Rows[0][0].ToString(); 


    }

Note: This is neither the best not the appropriate way of doing things. There isn't any exception handling etc.

0
bas On

I would make GetEmployee return an actual Employee type.

public Employee getEMP(string name1)
{
    // left out some of your code intentionally
    da.SelectCommand = new SqlCommand("select * from pss where Emp_code='"+name1+"'", dbconn);
    DataSet ds = new DataSet();
    da.Fill(ds);
    dbconn.Close();
    return new Employee(ds);
}

And define a class Employee that would look like

public class Employee
{
    public string Name { get; set; }
    /* Other properties ... */ 

    public Employee(DataSet dataset)
    {
        Name = ds.Tables[0].Rows[0][0].ToString();
        // etc
    }
}

That way your UI layer can talk to actual objects (entities), instead of having to bother with magic numbers in DataSets, and for example rely on data binding in your UI.

private void btn_search_Click(object sender, EventArgs e)
{
    string empcode=txt_empcode.Text;
    Test_DAL obj1= new Test_DAL();

    var employee = obj1.getEMP(empcode);

    dg.DataSource = employee;
}