//update data into datatable public static bool Update(ContactClass c) { //Creating a default return type and setting its value to false bool isSuccess = false; //Step 1: connect database SqlConnection conn = new SqlConnection(myconStr); try { //Step 2: Create a sql query to insert data string sql = "UPDATE tbl_contact SET FirstName=@FirstName,LastName=@LastName,ContactNumber=@ContactNumber,Address=@Address,Gender=@Gender where ContactID=@ContactID)"; //creating SQL command using sql and conn SqlCommand cmd = new SqlCommand(sql, conn); //Create Parameters to add data cmd.Parameters.AddWithValue("@FirstName", c.FirstName); cmd.Parameters.AddWithValue("@LastName", c.LastName); cmd.Parameters.AddWithValue("@ContactNumber", c.ContactNumber); cmd.Parameters.AddWithValue("@Address", c.Address); cmd.Parameters.AddWithValue("@Gender", c.Gender); cmd.Parameters.AddWithValue("@ContactID", c.ContactID); //connection open here conn.Open(); int rows = cmd.ExecuteNonQuery(); //if query run successfully then the value of rows will be grater then 0 , else it will be zero if (rows > 0) { isSuccess = true; } else { isSuccess = false; } } catch (Exception ex) { } finally { conn.Close(); } return(isSuccess); }
//delete data into datatable public static bool Delete(ContactClass c) { //Creating a default return type and setting its value to false bool isSuccess = false; //Step 1: connect database SqlConnection conn = new SqlConnection(myconStr); try { //Step 2: Create a sql query to insert data string sql = "Delete from tbl_contact where ContactID = @ContactID)"; //creating SQL command using sql and conn SqlCommand cmd = new SqlCommand(sql, conn); //Create Parameters to add data SqlParameter p = new SqlParameter("@ContactID", SqlDbType.Int); p.Value = c.ContactID; cmd.Parameters.Add(p); //connection open here conn.Open(); int rows = cmd.ExecuteNonQuery(); //if query run successfully then the value of rows will be grater then 0 , else it will be zero if (rows > 0) { isSuccess = true; } else { isSuccess = false; } } catch (Exception ex) { } finally { conn.Close(); } return(isSuccess); }
private void button1_Click(object sender, EventArgs e) { a1.FirstName = textBox2.Text; a1.LastName = textBox3.Text; a1.ContactNumber = textBox4.Text; a1.Address = richTextBox1.Text; a1.Gender = comboBox1.Text; //inserting data into DB bool success = ContactClass.Insert(a1); if (success == true) { MessageBox.Show("Successfully Inserted."); clear(); } else { MessageBox.Show("failed To Add Contact"); } updateDisplay(); }