Márton Gergő
Márton Gergő

Reputation: 109

C# SQL to labels printing out

Lets say I have a SQL database named Login and have a table in it called LoggedIn with column name and clockin and we don't know how many rows does it have.

In C# I want to print out all these data into seperate labels like so:

Label Image

SqlConnection con = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\gregg\Desktop\KFC\Data.mdf; Integrated Security = True; Connect Timeout = 30");

DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(query, con);

con.Open();
da.Fill(dt);
con.Close();

int x = 1;
DataRow row1 = dt.Rows[x];


for (int i = 0; i < x; i++)
{
     if (row1 == null)
     {
         MessageBox.Show("ERROR");
     }
     else
     {
         switch (x)
         {
             case 1:
                 label1.Text = row1["name"].ToString();
                 label4.Text = row1["clockin"].ToString();
                 x++;
             break;
             case 2:
                 label2.Text = row1["name"].ToString();
                 label5.Text = row1["clockin"].ToString();
                 x++;
             break;
             case 3:
                 label3.Text = row1["name"].ToString();
                 label6.Text = row1["clockin"].ToString();
                 x++;
             break;
             case 4:
                 label7.Text = row1["name"].ToString();
                 label8.Text = row1["clockin"].ToString();
                 x++;
             break;
             default: MessageBox.Show("ERROR");
             break;
        }

    }

}

Currently this is my code for this part. I'm open minded for other ways of solving this problem.

Upvotes: 1

Views: 377

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415690

Don't create or set individual controls for this, not on the form and not even in a loop.

Instead, look for an option that lets you bind to a datasource. The DataGrid and FlowLayoutPanel controls are both good options here.

Assuming a DataGrid where you've already setup the columns and mapping, the code will look like this:

DataTable dt = new DataTable();
using (var con = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\gregg\Desktop\KFC\Data.mdf; Integrated Security = True; Connect Timeout = 30"))
{     
    SqlDataAdapter da = new SqlDataAdapter(query, con);
    da.Fill(dt);
    DataGrid1.DataSource = dt;
}

That's it.

Upvotes: 1

Related Questions