Click here to Skip to main content
15,921,941 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how checkedboxitem is selected when it is fetch from database in checkedbox list. what i tried is

What I have tried:

SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["Conec"].ConnectionString);
           SqlCommand cmd3;
           string sql3 = " SELECT Task From Todaywork where Username='" + Login.recuser + "' and Active='1'";
           try
           {
               con3.Open();
               cmd3 = new SqlCommand(sql3, con3);
               string item = cmd3.ExecuteScalar().ToString();
               cmd3.Dispose();
               con3.Close();


               checkedListBoxongoing.SelectedItem = item;





           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.Message);

           }
Posted
Updated 15-Jul-20 3:43am

1 solution

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

You should also wrap your command and connection objects in using blocks to ensure they're always disposed of properly.

And you'll need to deal with cases where your command returns null:
C#
const string sql3 = "SELECT Task FROM Todaywork WHERE Username = @Username AND Active = '1'";

using (SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["Conec"].ConnectionString))
using (SqlCommand cmd3 = new SqlCommand(sql3, con3))
{
    cmd3.Parameters.AddWithValue("@Username", Login.recuser);
    
    con3.Open();
    object result = cmd3.ExecuteScalar();
    if (result != null && !Convert.IsDBNull(result))
    {
        checkedListBoxongoing.SelectedItem = Convert.ToString(result);
    }
}


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[^]
 
Share this answer
 
v2
Comments
Member 14852747 15-Jul-20 13:00pm    
it give me error of object reference was not set....Command was null
Richard Deeming 15-Jul-20 13:11pm    
Typo in the solution - command.ExecuteScalar() should be cmd3.ExecuteScalar().

However, the error is concerning. It suggests you have another command object stored somewhere which is not wrapped in a using block. You should check that as well.
Member 14852747 15-Jul-20 13:32pm    
Still not working even i rechecked the code
Richard Deeming 16-Jul-20 5:14am    
"Not working" isn't a useful comment. You need to explain precisely what the problem is.

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