filmov
tv
Deleting data from gridview using objectdatasource control - Part 15

Показать описание
Link for text version of this video
Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.
We will be using tblEmployee table for this demo. For SQL script to create and populate this table, please refer to, Part 13 - Deleting data from gridview using sqldatasource control.
Steps to delete from gridview using objectdatasource control the following are the steps.
1. Create EmployeeDataAccessLayer class
3. Add a static method to select all employees in EmployeeDataAccessLayer class
4. Add a static method to delete employee record using EmployeeId, in EmployeeDataAccessLayer class
5. Configure objectdatasource and gridview control.
6. Set "EmployeeId" as the value for DataKeyNames property of the gridview control.
Now let us look at the steps in detail.
Step 1: Create EmployeeDataAccessLayer class
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
}
Step 3: Add a static method to select all employees in EmployeeDataAccessLayer class
Step 4: Add a static method to delete employee record using EmployeeId, in EmployeeDataAccessLayer class
public static void DeleteEmployee(int EmployeeId)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("Delete from tblEmployee where EmployeeId = @EmployeeId", con);
cmd.Parameters.Add(param);
con.Open();
cmd.ExecuteNonQuery();
}
}
Step 5: Configure objectdatasource and gridview control.
Compile the project. If the project is not compiled, EmployeeDataAccessLayer class may not show up in the wizard when configuring objectdatasource control.
1. Right click on "ObjectDataSource1" control and select "Show Smart Tag"
2. Now click on "Configure Data Source" link
3. Select "EmployeeDataAccessLayer" class from "Choose your business object dropdownlist" and click next
4. On "Define Data Methods" screen, select "GetAllEmployees" method
5. Now click on "DELETE" tab and select "DeleteEmployee" method and click Finish
Now, associate "ObjectDataSource1" with "GridView1"
Step 6: Set "EmployeeId" as the value for DataKeyNames property of the gridview control.
This can be done in HTML or code. Since, EmployeeId is the primary key, we need to set it as the value for "DataKeyNames" property of the gridview control, otherwise deleting does not work.
Комментарии