Home > DeveloperSection > Forums > code optimized in c#
Goti Bandu

Total Post:119

Points:835
Posted on    November-16-2012 4:36 AM

 C# C# 
Ratings:


 2 Reply(s)
 1964  View(s)
Rate this:
hello every one,

===============================================================================

public static int SetSelectedItem(string[] sValues)
        {
            int nRow = 0;
            try
            {
                foreach (string str in sValues)
                {
                    SqlCommand cmdUpdate = new SqlCommand("UPDATE [dbo].[tblProductsManager] SET IsActive = 1 WHERE Id= '" + str + "' ", con);
                    if (con.State == ConnectionState.Closed)
                        con.Open();
                    nRow = cmdUpdate.ExecuteNonQuery();
                }
            }
            catch { }
            finally
            {
                if (con.State == ConnectionState.Open)
                    con.Close();
            }
            return nRow;
        }

======================================================================

in the above code, "cmdUpdate.ExecuteNonQuery();" call for every value of "sValues".
i want, "cmdUpdate.ExecuteNonQuery();" execute only one time for all array value.
if have any idea, plz help me.


Arun Singh

Total Post:68

Points:476
Posted on    November-19-2012 2:11 AM

Hi Goti Bandhu,
You can use StringBuilder concept here, replace your code with following code:
public static int SetSelectedItem(string[] sValues)
        {
            int nRow = 0;
            try
            {
               StringBuilder sqlQuery = new StringBuilder ();
               sqlQuery.Append("UPDATE [dbo].[tblProductsManager] SET IsActive = 1 WHERE Id in '('");
          foreach (string str in sValues)
                {
                    sqlQuery.Append(str+"'," );
                   
                }
               sqlQuery.Append("')" );
              SqlCommand cmdUpdate = new SqlCommand ( sqlQuery.ToString(), con);
                   if (con.State == ConnectionState.Closed)
                        con.Open();
                    nRow = cmdUpdate.ExecuteNonQuery();
            }
            catch { }
            finally
            {
                if (con.State == ConnectionState.Open)
                    con.Close();
            }
            return nRow;
        }
Please mark as answer if this code will resolve your problem.

Goti Bandu

Total Post:119

Points:835
Posted on    November-19-2012 2:14 AM



It resolve my problem

Thanks

Don't want to miss updates? Please click the below button!

Follow MindStick