Answers for "a label given to column database"

0

set label from database

protected string conS = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Databees.mdf;Integrated Security=True;User Instance=True";
protected SqlConnection con;

protected void Page_Load(object sender, EventArgs e)
{
    con = new SqlConnection(conS);
    try
    {
        con.Open();
        string q = "SELECT * FROM tblKLanten;";
        SqlCommand query = new SqlCommand(q, con);

        using (SqlDataReader dr = query.ExecuteReader())
        {
            bool success = dr.Read();
            if (success)
            {
                Label1.Text = dr.GetString(1);
            }
        }

        con.Close();
    }
    catch (Exception ex)
    {
        Label2.Text = "Error";
    }
}
Posted by: Guest on September-15-2021
0

set label from database

Well, with the information provided it's not terribly easy to answer, but let's assume your structure is like this:

CREATE TABLE tblKLanten (
    ID INT,
    Klantnummer VARCHAR(50)
)
you'll need to get the field by the index from the reader like this:

Label1.Text = dr.GetString(1);
but you're also going to need to read, so you'll need to issue this statement before setting the label:

bool success = dr.Read();
if (success)
{
    // set the label in here
}
but 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:

protected string conS = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Databees.mdf;Integrated Security=True;User Instance=True";
protected SqlConnection con;

protected void Page_Load(object sender, EventArgs e)
{
    con = new SqlConnection(conS);
    try
    {
        con.Open();
        string q = "SELECT * FROM tblKLanten;";
        SqlCommand query = new SqlCommand(q, con);

        using (SqlDataReader dr = query.ExecuteReader())
        {
            bool success = dr.Read();
            if (success)
            {
                Label1.Text = dr.GetString(1);
            }
        }

        con.Close();
    }
    catch (Exception ex)
    {
        Label2.Text = "Error";
    }
}
Posted by: Guest on September-15-2021

Code answers related to "a label given to column database"

Browse Popular Code Answers by Language