Click here to Skip to main content
15,917,177 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
see the below code:
I want to insert three values, such as Id,Name,address but using this code it insert only address column value in the database.

XML
public static int Dynamicarray(string connectionString, Dictionary<string, object> parameters)
    {
        using (SqlConnection con = Database.GetConnection())
        {

            string column_name="";
            string value="";
            foreach (KeyValuePair<string, object> kvp in parameters)
            {
                column_name =RemoveSpecialChars(kvp.Key + ",".TrimEnd(','));
                value = kvp.Key+",".TrimEnd(',');
            }
            SqlCommand cmdExecute = new SqlCommand("insert into tbl2 ("+column_name+") values("+value+")",con);
            foreach (KeyValuePair<string, object> kvp in parameters)
            {
                cmdExecute.Parameters.AddWithValue(kvp.Key, kvp.Value);
            }
               return cmdExecute.ExecuteNonQuery();
        }
    }


Please help me in this regard.

Thanks in Advance.
Posted
Updated 17-May-11 2:31am
v2

If we ignore that you are concatentating strings (please, look at using a StringBuilder - it's a lot more efficient for that kind of thing), then your problem is here:
C#
column_name =RemoveSpecialChars(kvp.Key + ",".TrimEnd(','));
The "column_name" string will always be the last key, followed by a comma...
 
Share this answer
 
I think the problem is here

foreach (KeyValuePair<string,> kvp in parameters)
            {
                column_name += RemoveSpecialChars(kvp.Key + ",".TrimEnd(','));
                value += kvp.Key+",".TrimEnd(',');
            }
 
Share this answer
 
Comments
Manfred Rudolf Bihy 17-May-11 9:03am    
Correct! 5+
Well spotted!
rahul dev123 17-May-11 9:10am    
I use this but it not separated the string. It should be like that:
IdNameAddresss or values(@Id@Name@Address).
Can you help me..

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