1

It is possible to populate many labels from one SqlCommand instead of writing many SqlCommand?

For example

select name from users where ID=1
select name from users where ID=2
select name from users where ID=3
select name from users where ID=4

Label1.Text = //here should be ID 1
Label2.Text = //here should be ID 2
Label1.Text = //here should be ID 3
Label2.Text = //here should be ID 4

So I ask - is it possible using just one SqlCommand?

10
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. Commented Dec 27, 2018 at 16:12
  • I ask how/or if is possible to using one sql command to populate multiple Labels with different ID like where ID=1-for Label1 Text , where ID=2 for label2.text Commented Dec 27, 2018 at 16:18
  • Are you using ADO.NET, LINQ to SQL or Entity Framework? Commented Dec 27, 2018 at 16:23
  • 1
    Then you are using ADO.NET, which is when you use SqlConnection directly (or some other provider that implements System.Data.Common.DbConnection. Commented Dec 27, 2018 at 16:43
  • 1
    If you want multiple records to come back from the database, consider rewriting your sql where clause or eliminating it altogether. No need for multiple select statements. For instance, "Select name from users" or "Select name from users where ID between @x and @y". Then use a repeater or some sort of loop to fill your labels dynamically in your UI. Commented Dec 27, 2018 at 17:04

1 Answer 1

2

As per your confirmation that you use ADO.NET, here is what you are looking for-

SqlConnection con = new SqlConnection(@"server=localhost; database=Site; trusted_connection=true;"); 
con.Open(); 
SqlCommand cmd = new SqlCommand(@"select id, name from users where ID Between 1 and 4", con); 
SqlDataReader dr = cmd.ExecuteReader(); 
while (dr.Read()) 
{
   if(dr["id"].ToString() == "1")
     Label1.Text = dr["Name"].ToString();
   else if(dr["id"].ToString() == "2")
     Label2.Text = dr["Name"].ToString();
   else if(dr["id"].ToString() == "3")
     Label3.Text = dr["Name"].ToString();
   else if(dr["id"].ToString() == "4")
     Label4.Text = dr["Name"].ToString();
} 
dr.Close(); 
con.Close(); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir. This is what i need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.