CODE OPTIMIZED IN C#

Goti Bandu

Total Post:119

Points:835
Posted by  Goti Bandu
C# 
C#
 2333  View(s)
Ratings:
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.
  1. Arun Singh

    Post:68

    Points:476
    Re: code optimized in c#

    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.

  1. Goti Bandu

    Post:119

    Points:835
    Re: code optimized in c#



    It resolve my problem

    Thanks

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!