How to connect windows form label to Sql Server Table ?

zachary marcotte 21 Reputation points
2022-02-16T02:06:38.5+00:00

Hi, I'm actually creating a pool hockey league database application. I wonder if it is possible to connect my application label with table in Sql server. For example, a player's points are shown in a label text. This label text is connected to a Sql Server Table With all players's stats, but to a specific column for a specific lign (player). When I update the players's stats in the Sql Server, I want that it also update in all the person that have installed my application. Thanks for your help

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,883 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,819 questions
{count} votes

Accepted answer
  1. Jack J Jun 24,501 Reputation points Microsoft Vendor
    2022-02-17T03:21:04.92+00:00

    @zachary marcotte , you could try the following code to show the label text from sql serer table.

     private void button1_Click(object sender, EventArgs e)  
            {  
                string connstr = @"connstr";  
                SqlConnection connection=new SqlConnection(connstr);  
                string sql = string.Format("select Score from Hockey where Name='{0}'",textBox1.Text);  
                connection.Open();  
                SqlCommand cmd = new SqlCommand(sql, connection);  
                SqlDataReader reader = cmd.ExecuteReader();  
                while(reader.Read())  
                {  
                    label1.Text = reader["Score"].ToString();  
                }  
                 
      
            }  
    

    Database:

    175176-image.png

    Result in the winform:

    175107-3.gif

    You can change your code appropriately according to my code.

    Hope this could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,401 Reputation points
    2022-02-17T10:33:04.827+00:00

    Look at using SqlDependency object to detect changes and react to them, in this case to your label.

    https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/detecting-changes-with-sqldependency

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.