{
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");
}
}