Click here to Skip to main content
15,906,558 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to create a class file in asp.net c# for update command.

How can I create update command using array?
I can't declare the update command statically because its different for different tables.

Please help me how to create this and how to declare array and call the function in our asp.net page.

Thanks in advance.
Posted
Updated 16-May-11 21:25pm
v2
Comments
Sergey Alexandrovich Kryukov 17-May-11 2:49am    
Not clear. What is "class file"? What the class should do? Why what you want is a problem?
--SA
Dalek Dave 17-May-11 3:25am    
Edited for Grammar and Readability.

Here is a generic routine to do it:
/// <summary>
/// Update a database entry with new field data
/// </summary>
/// <param name="table">Name of table to update</param>
/// <param name="fieldsList">Comma separated list of fields to be updated</param>
/// <param name="condition">If not null, condition of form "ID=@1".
/// The first parameter in the 'parameters' list will be the condition '@1'</param>
/// <param name="parameters">List of parameters to update with</param>
public static void Update(string table, string fieldsList, string condition, params object[] parameters)
    {
    StringBuilder sb = new StringBuilder(1000);
    sb.Append(string.Format("UPDATE {0} SET ", table));
    string[] fields = fieldsList.Split(',');
    int firstSetting = (string.IsNullOrEmpty(condition) ? 0 : 1);
    if ((fields.Length + firstSetting) > parameters.Length)
        {
        throw new ArgumentException("Not enough parameters for this field list");
        }
    string prefix = "";
    for (int i = 0; i < fields.Length; i++)
        {
        firstSetting++;
        sb.Append(string.Format("{0}{1}=@{2}", prefix, fields[i],firstSetting.ToString()));
        prefix = ",";
        }
    sb.Append(" " + (string.IsNullOrEmpty(condition) ? "" : "WHERE " + condition));
    Execute(sb.ToString(), parameters);
    }
/// <summary>
/// Execute an Sql command with parameters, and return the command
/// object for later use.
/// Parameters are added as "@1", "@2", etc.
/// </summary>
/// <param name="sql">SQL command</param>
/// <param name="parameters">List of parameters to add.</param>
/// <returns>Constructed SQL object</returns>
private static SqlCommand Execute(string sql, params object[] parameters)
    {
    SqlCommand cmd = new SqlCommand(sql, con);
    Execute(cmd, parameters);
    return cmd;
    }
/// <summary>
/// Execute an Sql command with parameters
/// Parameters are added as "@1", "@2", etc.
/// </summary>
/// <param name="cmd">SQL command object</param>
/// <param name="parameters">List of parameters to add.</param>
private static void Execute(SqlCommand cmd, params object[] parameters)
    {
    AddParameters(cmd, parameters);
    cmd.ExecuteNonQuery();
    }
/// <summary>
/// Add all the parameters to the SQL Command object
/// Parameters are added in order as '@1', '@2', etc.
/// Replaces null with DBNull.Value
/// </summary>
/// <param name="cmd">SQL Command to add to</param>
/// <param name="parameters">List of parameters to add</param>
private static void AddParameters(SqlCommand cmd, object[] parameters)
    {
    int i = 1;
    cmd.Parameters.Clear();
    foreach (object o in parameters)
        {
        if (o == null)
            {
            cmd.Parameters.AddWithValue("@" + i++, DBNull.Value);
            }
        else
            {
            cmd.Parameters.AddWithValue("@" + i++, o);
            }
        }
    }
 
Share this answer
 
Comments
rahul dev123 17-May-11 3:05am    
Thanks for your help but i wan't to know how to pass parameters,what is fieldlist and what is the condition
OriginalGriff 17-May-11 3:34am    
Read them properly.
Dalek Dave 17-May-11 3:25am    
Good answer.
If I understand you correctly, you want to update several different tables using only one function. This can be done if you are using Stored Procedures in your DataBase with a function like this:

C#
public int ExecuteNonQuery(string connectionString, string spName, Dictionary<string,object> parameters)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmdExecute = new SqlCommand(spName, con);
                cmdExecute.CommandType = System.Data.CommandType.StoredProcedure;
                foreach (KeyValuePair<string, object> kvp in parameters)
                {
                    cmdExecute.Parameters.AddWithValue(kvp.Key, kvp.Value);
                }
                con.Open();
                return cmdExecute.ExecuteNonQuery();
            }
        }


where spName is the name of the Stored Procedure, and the Dictionary<string,> contains your parameters, so you would call it like this:

C#
public void Update()
        {
            Dictionary<string,> parameters = new Dictionary<string,>();
            parameters.Add("@Param1", param1Value);
            parameters.Add("@Param2", param2Value);
            int rowsAffected = ExecuteNonQuery("yourConnectionString", "yourStoredProcName", parameters);
        }


Hope this helps
 
Share this answer
 
Comments
rahul dev123 17-May-11 3:11am    
Thanks for your help but i want to know if i declare stored procedure then it is static for a table. I have to write different stored procedure for different tables or if we required different columns to update then how can it is working because in stored procedure we have to declare the columns name?
Wayne Gaylard 17-May-11 3:31am    
Whatever goes on in your application does not really matter, as the tables and columns in the database must already be defined. You cannot have dynamic tables in a database. Therefore, if you know the names of the tables and columns you can write the stored procedures.
rahul dev123 17-May-11 3:37am    
Thanks,i use this command but in the second part
public void update()
{
}
in this code shows various errors. It not support Dictionary etc.Please help
Wayne Gaylard 17-May-11 3:52am    
That part was just to show you how to call the function. You would need to substitute your own parameters. To use a Dictionary<> you need to include System.Collections.Generic in your class file.
rahul dev123 17-May-11 5:05am    
If i required one more columns to be updated. Then how can i do that, again need to create another procedure or update the procedure. But i need to create command at only one time. what is the solution?

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