public static string updateToDatabase(object obj, string type, string table, string user) { string message = "", query = "", autoid = "", columns = ""; try { if (type == "insert") { foreach (var prop in obj.GetType().GetProperties()) { if (prop.Name != "autoid") { switch (prop.GetType().Name) { case "Int32": case "Decimal": query += prop.GetValue(obj, null) == null ? "NULL," : prop.GetValue(obj, null).ToString() + ","; break; default: query += prop.GetValue(obj, null) == null ? "NULL," : "'" + prop.GetValue(obj, null).ToString().Replace("'", "''") + "',"; break; } columns += prop.Name + ","; } } query = query.TrimEnd(','); columns = columns.TrimEnd(','); //make query query = "insert into " + table + " (" + columns + ") values (" + query + ")"; query = query.Replace(",''", ",NULL"); query = query.Replace("'',", "NULL,"); //add to database DataTable dtinput = new DataTable(); DataSet dsoutput = new DataSet(); dtinput.Columns.Add("data"); dtinput.Columns.Add("value"); dtinput.Rows.Add("@user", user); dtinput.Rows.Add("@data_str", query); dsoutput = new clsCommonFunction().callProcedure("usp_insert_data", dtinput, 1); message = "0|Success"; } else if (type == "update") { foreach (var prop in obj.GetType().GetProperties()) { if (prop.Name != "autoid") { switch (prop.GetType().Name) { case "Int32": case "Decimal": query += prop.GetValue(obj, null) == null ? prop.Name + "=NULL," : prop.Name + "=" + prop.GetValue(obj, null).ToString() + ","; break; default: query += prop.GetValue(obj, null) == null ? prop.Name + "=NULL," : prop.Name + "='" + prop.GetValue(obj, null).ToString().Replace("'", "''") + "',"; break; } } else if (prop.Name == "autoid") { autoid = prop.GetValue(obj, null).ToString(); } } query = query.TrimEnd(','); //make query query = "update " + table + " set " + query + " where autoid=" + autoid; query = query.Replace("=''", "=NULL"); //add to database DataTable dtinput = new DataTable(); DataSet dsoutput = new DataSet(); dtinput.Columns.Add("data"); dtinput.Columns.Add("value"); dtinput.Rows.Add("@user", user); dtinput.Rows.Add("@data_str", query); dsoutput = new clsCommonFunction().callProcedure("usp_insert_data", dtinput, 1); message = "0|Success"; } } catch (Exception ex) { generatelog(null, null, "updateToDatabase", ex.Message + ex.StackTrace + "(" + query + "-" + columns + ")"); message = ex.Message + "|2"; } return(message); }