I am trying to use the following code to Save or update the data from 4 text boxes into MS SQL database. There is no error but the data is not reflecting in the database. Can you please correct me if I am doing something wrong?
public partial class Form1 : Form
{
private string connString;
private SqlConnection connection;
private SqlCommand command;
private bool addNew;
public Form1()
{
addNew = false;
connString = ConfigurationManager.ConnectionStrings["societyConnectionString"].ConnectionString;
connection = new SqlConnection(connString);
command = connection.CreateCommand();
InitializeComponent();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
command.CommandType = CommandType.Text;
if (addNew)
{
command.CommandText = "INSERT INTO [Members] VALUES (@MemberId, @Name, @Age, @City)";
addNew = false;
}
else
{
command.CommandText = "UPDATE [Members] SET Name=@Name, Age=@Age, City=@City WHERE MemberId=@MemberId";
}
SqlParameter id = new SqlParameter("@MemberId", int.Parse(txtId.Text));
SqlParameter name = new SqlParameter("@Name", txtName.Text);
SqlParameter age = new SqlParameter("@Age", int.Parse(txtAge.Text));
SqlParameter city = new SqlParameter("@City", txtCity.Text);
command.Parameters.Clear();
command.Parameters.Add(id);
command.Parameters.Add(name);
command.Parameters.Add(age);
command.Parameters.Add(city);
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
int rowsAffected = command.ExecuteNonQuery();
connection.Close();
MessageBox.Show(rowsAffected.ToString() + "rows affected");
}
}
After executing, message box shows '1', but if i see the database, there is no updated data.
Adavesh ManagaonPosted Jun 6, 2010, 12:49 PM
CrishPosted Jun 6, 2010, 1:41 AM
try below query for insert..
INSERT INTO [Members] (MemberId, Name, Age, City) VALUES (@MemberId, @Name, @Age, @City)";
...
Also, check Your MemberId Identity set not to AutoIncremented. If this Id is AutoIncremented then no need to pass in Insert query.
Don't forget to Mark Do you like this Answer
that solved your problem!