Chuki2 Chuki2 - 1 month ago 8
SQL Question

Take value from query to label in C#

How can i take value from query result to label?

I have two label, one is labelName and one more is labelDepartment

So when i run the query, how can i get value from query result and assign it to label using c#?

This is my Sql Command:

"SELECT tbl_staff.staffName,tbl_department.department
FROM tbl_staff,tbl_logs,tbl_department
WHERE tbl_staff.userID = tbl_logs." + listStaff.SelectedValue + " and tbl_staff.idDepartment = tbl_department.idDepartment;"


This is current code in C#

//Open SQL connection

SqlConnection openCon = new SqlConnection(connString);
openCon.Open();

string SQL = string.Format("SELECT tbl_staff.staffName,tbl_department.department FROM tbl_staff,tbl_logs,tbl_department WHERE tbl_staff.userID = tbl_logs.userID and tbl_staff.idDepartment = tbl_department.idDepartment" + listStaff.SelectedValue + ";");


SqlCommand command = new SqlCommand(SQL);
SqlDataReader reader = command.ExecuteReader();

while(reader.Read())
{
labelName.Text = reader["tbl_staff.staffName"];
labelDepartment.Text = reader["tbl_department.department"];
}


Note : Our record will return one row only..
MS SQL and C#.. thanks for help...;)

Answer
        string name = null;
        string department = null;
        string listStaff = "MylistStaff";

        string sql =  "SELECT tbl_staff.staffName,tbl_department.department " +
            "FROM tbl_staff,tbl_logs,tbl_department " +
            "WHERE tbl_staff.userID = tbl_logs." + listStaff + " and tbl_staff.idDepartment = tbl_department.idDepartment;";
        //change this connection string... visit www.connectionstrings.com
        string connString = "Server=localhost; Database=myDatabaseName; Trusted_Connection=Yes";
        using (SqlConnection conn = new SqlConnection(connString))
        {
            conn.Open();
            using (SqlCommand command = new SqlCommand(sql,conn))
            {
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    name = reader[0] as string;
                    department = reader[1] as string;
                    //break for single row or you can continue if you have multiple rows...
                    break;
                }
            }
            conn.Close();
        }

department and listStaff can then easily be applied to label text like:

DepartmentLabel.Text = department;