Wednesday, March 18, 2009

Update Query with where Clause in a seperate Class

Create a method of Update in a seperate Class

public bool Update(string customerId, string customerName, string customerPhone, string customerAddress, string customerAge)
{
SqlCommand objCommand = new SqlCommand();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString);
SqlParameter objParameter = new SqlParameter();
try
{
string strSql = "UPDATE Customer "+
"SET CustomerName = @CustomerName, CustomerPhone = @CustomerPhone, CustomerAddress = @CustomerAddress, "+
"CustomerAge = @CustomerAge WHERE CustomerID = @CustomerID";
objCommand.CommandText = strSql;
objCommand.Connection = conn;
objParameter = new SqlParameter("@CustomerID", customerId);
objCommand.Parameters.Add(objParameter);
objParameter = new SqlParameter("@CustomerName", customerName);
objCommand.Parameters.Add(objParameter);
objParameter = new SqlParameter("@CustomerPhone", customerPhone);
objCommand.Parameters.Add(objParameter);
objParameter = new SqlParameter("@CustomerAddress", customerAddress);
objCommand.Parameters.Add(objParameter);
objParameter = new SqlParameter("@CustomerAge", customerAge);
objCommand.Parameters.Add(objParameter);
objCommand.Connection.Open();
return (objCommand.ExecuteNonQuery() > 0 ? true : false);
}
catch (Exception ex)
{
conn.Close();
return false;
}
finally
{
conn.Close();
}
}

Create a object of Update on the update button click event which get CustomerId through Query String


int customerid = Convert.ToInt32(Request.QueryString["CustomerId"].ToString());
Customer objCustomer = new Customer();
objCustomer.Update(customerid.ToString(), tbxCustomerName.Text.Trim(), tbxCustomerPhone.Text.Trim(), tbxCustomerAddress.Text.Trim(), tbxCustomerAge.Text.Trim());

No comments:

Post a Comment