Click here to Skip to main content
15,843,865 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to change a labels text based on what the users selects from a dropdownlist which is populated from a sql server. The labels text should be the result of a query which is called when the users select something from the dropdownlist. The lists are pretty long.

Example
User selects that their job title is a janitor from the dropdownlist.
The label changes the the office code number of what a janitor should be.

Users selects: Janitor
Label changes to code: 54684.

What I have tried:

using (SqlConnection conn = new SqlConnection("Database connection"))
                
{string myqueryconvt = "Select Office_Symbols FROM Office_Symbol_ID WHERE Office_Names = '" + ddlOfficeSymbolConvt.Text + "';";
SqlCommand cmd1 = new SqlCommand(myqueryconvt, conn);

lblOffice_SymbolsCovnt.Text = //???? I'm not sure what to call from this point If this is even correct.
Posted
Updated 5-Jun-19 15:16pm

You can use the ExecuteScalar method, see example here: Obtaining a Single Value from a Database | Microsoft Docs[^]
 
Share this answer
 
Quote:
C#
"Select Office_Symbols FROM Office_Symbol_ID WHERE Office_Names = '" + ddlOfficeSymbolConvt.Text + "';"

Not like that!

Your code is almost certainly vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

C#
using (SqlConnection conn = new SqlConnection("Database connection"))
using (SqlCommand cmd = new SqlCommand("Select Office_Symbols FROM Office_Symbol_ID WHERE Office_Names = @Office_Names;", conn))
{
    cmd.Parameters.AddWithValue("@Office_Names", ddlOfficeSymbolConvt.Text);
    
    conn.Open();
    
    object result = cmd.ExecuteScalar();
    if (Convert.IsDBNull(result))
    {
        lblOffice_SymbolsCovnt.Text = string.Empty;
    }
    else
    {
        lblOffice_SymbolsCovnt.Text = Convert.ToString(result);
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900