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 r
One way to do:
private void getData()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING HERE");
connection.Open();
SqlCommand sqlCmd = new SqlCommand(" 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", connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlCmd.Parameters.AddWithValue("@username",user);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
lable.Text = dt.Rows[0]["staffName"].ToString(); //Where "staffName" is ColumnName
}
connection.Close();
}
Suggest to use a stored procedure not in line query to avoid SQL injection attacks.
stored procedure example
Check this one - Also set your connection string along with this code
SQLCommand command = new SQLCommand();
command.CommandText = " 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 ";
SQLDataReader reader = command.executeReader();
while(reader.read())
{
labelName.Text = reader.GetString(0);
labelDepartment.Text = reader.GetString(1);
}
Populate the Dataset with your Query and then retrieve values from Dataset and assign it to your label.
Lets say your Dataset is DS then:
labelName.Text=DS.Tables[0]["tbl_staff.staffName"].tostring();
labelDepartment.Text=DS.Tables[0]["tbl_department.department"].tostring();
Hope this helps.
you need to read the result via a SQLDataReader
SQLCommand command = new SQLCommand("your sql string here");
SQLDataReader reader = command.executeReader();
while(reader.read())
{
set your label values here with reader["cloumn"]
}
You can read content of the row(s) that query returned using DataReader
class. It has methods to get single value, or you can iterate for each row. Tell me how many rows youR query returns so I can provide the exact code.
//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"].ToString();
labelDepartment.Text = reader["tbl_department.department"].ToString();
}
Convert Type is what you left in your code....