Click here to Skip to main content
15,891,375 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi, i am working with combobox in my windowsForm project.
I get an attribute "LIB" from sql server table value showed in the combobox.
I need to get another attribute "GUID" of the selectedItem and pass it from the first Form (FormMaster) to another Form (FormImport).

What I have tried:

C#
int ScénarioIndex = comboBox3.SelectedIndex;                     
             SqlCommand cmd = new SqlCommand("SELECT [OID] FROM [AffecAnalytique].[dbo].[DESCRIPTIF] WHERE [LIBELLE]='" + comboBox3.Items[ScénarioIndex] + "' ", con);
             con.Open();
             SqlDataReader rdr = cmd.ExecuteReader();
             if (rdr.HasRows)
             {
                 string strOIDe = (string)rdr["OID"];
                 MessageBox.Show(strOIDe,"OID"); 
             }
             con.Close();
Posted
Updated 30-Sep-20 5:40am
Comments
Richard MacCutchan 30-Sep-20 6:13am    
Where is the GUID, in the ComboBox or the database?
houssem eddine ayari 30-Sep-20 8:32am    
In the database
Richard Deeming 30-Sep-20 7:10am    
SqlCommand cmd = new SqlCommand("SELECT [OID] FROM [AffecAnalytique].[dbo].[DESCRIPTIF] WHERE [LIBELLE]='" + comboBox3.Items[ScénarioIndex] + "' ", con);

Your code is 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[^]

using (SqlCommand cmd = new SqlCommand("SELECT [OID] FROM [AffecAnalytique].[dbo].[DESCRIPTIF] WHERE [LIBELLE] = @LIBELLE", con))
{
    cmd.Parameters.AddWithValue("@LIBELLE", comboBox3.Items[ScénarioIndex]);
    
    con.Open();
    object result = cmd.ExecuteScalar();
    if (result != null && !Convert.IsDBNull(result))
    {
        string strOIDe = (string)result;
        MessageBox.Show(strOIDe,"OID"); 
    }
}
houssem eddine ayari 30-Sep-20 8:38am    
Nothing is returned. Not even an empty messagebox
Richard Deeming 30-Sep-20 10:58am    
Then there is no matching record in your database.

1 solution

Your current binding is too simplistic. The following pattern is more useful for many situations, including your current one.

Get Selected Text and Value of ComboBox in Windows Application using C# and VB.Net[^]
 
Share this answer
 
Comments
houssem eddine ayari 1-Oct-20 5:17am    
I just have a question: how can I add a static text to the DisplayMember. comboBox3.DisplayMember ="LIBELLE"; --> get the data from DB.
I want the data to be showen in my combobox like this --> Scenario: LIBELLE

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