I have a problem that I couldn't find a solution to it, which is inserting data to LocalDB in Visual Studio Windows Form App - C#
Actually, I'm using a Class Library, and I added a reference to it in my Windows Form app
The problem is when I want to add new data to the local db, it doesn't show any errors, however, I see no data inserted into the database
This is my code in the Class Library, which is a general method the could be used to add any data to any table in the database
public virtual void Add(Item item)
{
int count = 0;
//create the first part of the Add SQL string
string addString = "INSERT INTO " + table + "(";
//add each field name from Item UpdateFields to the string
foreach (KeyValuePair<string, string> field in item.UpdateFields)
{
addString += "[" + field.Key + "]";
count++;
//add a comma when end of UpdateFields collection is reached
if (count < item.UpdateFields.Count)
{ addString += ", "; }
}
//start second part of Add string
addString += ") VALUES(";
count = 0;
//add each value from Item UpdateFields to the string
foreach (KeyValuePair<string, string> field in item.UpdateFields)
{
if (field.Value != null)
{ addString += "'" + field.Value.ToString() + "'"; }
else
{ addString += "NULL"; }
count++;
//add a comma when end of UpdateFields collection is reached
if (count < item.UpdateFields.Count)
{ addString += ", "; }
}
//add bracket at end of Add string
addString += ")";
command.CommandText = addString;
try
{
command.ExecuteNonQuery();
}
catch (SqlException ex)
{
item.Valid = false;
item.ErrorMessage = ex.Message;
}
}
and here where I'm using it to add an Account information
cc = new Account(accountID);
acc.UserName = userNametxt.Text;
acc.Password = "P@ssword";
acc.Email = emailtxt.Text;
acc.CreatedBy = "";
acc.Status = "1";
acc.LastLoginDateTime = null;
acc.LastFailureLoginDateTime = null;
accounts.Add(acc);
if (!acc.Valid)
{
MessageBox.Show(acc.ErrorMessage);
}
else
{
MessageBox.Show("Account has been added successfully!!");
}
and the following is my string connection
new SqlConnection(Properties.Settings.Default.TestConnectionString);
Thanks in advance