set label from database

Solutions on MaxInterview for set label from database by the best coders in the world

showing results for - "set label from database"
Christina
11 Apr 2019
1protected string conS = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Databees.mdf;Integrated Security=True;User Instance=True";
2protected SqlConnection con;
3
4protected void Page_Load(object sender, EventArgs e)
5{
6    con = new SqlConnection(conS);
7    try
8    {
9        con.Open();
10        string q = "SELECT * FROM tblKLanten;";
11        SqlCommand query = new SqlCommand(q, con);
12
13        using (SqlDataReader dr = query.ExecuteReader())
14        {
15            bool success = dr.Read();
16            if (success)
17            {
18                Label1.Text = dr.GetString(1);
19            }
20        }
21
22        con.Close();
23    }
24    catch (Exception ex)
25    {
26        Label2.Text = "Error";
27    }
28}
29
Chantelle
20 Jun 2018
1Well, with the information provided it's not terribly easy to answer, but let's assume your structure is like this:
2
3CREATE TABLE tblKLanten (
4    ID INT,
5    Klantnummer VARCHAR(50)
6)
7you'll need to get the field by the index from the reader like this:
8
9Label1.Text = dr.GetString(1);
10but you're also going to need to read, so you'll need to issue this statement before setting the label:
11
12bool success = dr.Read();
13if (success)
14{
15    // set the label in here
16}
17but remember, it's based off of the index of the column in the returned statement and so since you're issuing a SELECT * there's no way for me to know what the index is. In the end, I would recommend making some more changes, so consider the following code:
18
19protected string conS = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Databees.mdf;Integrated Security=True;User Instance=True";
20protected SqlConnection con;
21
22protected void Page_Load(object sender, EventArgs e)
23{
24    con = new SqlConnection(conS);
25    try
26    {
27        con.Open();
28        string q = "SELECT * FROM tblKLanten;";
29        SqlCommand query = new SqlCommand(q, con);
30
31        using (SqlDataReader dr = query.ExecuteReader())
32        {
33            bool success = dr.Read();
34            if (success)
35            {
36                Label1.Text = dr.GetString(1);
37            }
38        }
39
40        con.Close();
41    }
42    catch (Exception ex)
43    {
44        Label2.Text = "Error";
45    }
46}