Introduction
As we all know usage of Eval and Bind methods can be expensive. Controls that use this method with Data-Binding Expression are GridView, DetailsView, FormView, Repeater and ListView. These are actually Data-Bound controls which can be bound to Data Source controls such as an ObjectDataSource or SqlDataSource. There are ways to lower the cost of the usage of the Eval method. Here is an example of how to do this.
If you are using these controls (Data-Bound web controls) for enterprise web applications with several thousands of clicks per minute, the Eval method isn't really the best solution. And of course, everything is hard-coded in HTML. In this example we are NOT going to use Eval or Bind methods, we are NOT going to use Data Source controls. We are going to do everything from the server side.
Why ListView?
This control has one very important event that we are going to heavily manipulate - ItemDataBound. Also it has templates e.g. ItemTemplate and EditItemTemplate. Our example is going to bind the data from a DataSet, edit this data and update it.
Code explanation
We are going to have Label controls in ItemTemplate and TextBox controls in EditItemTemplate. In "edit mode" every Label is going to be switched with TextBox.
protected void Page_Load(object sender, EventArgs e)
{
if (ProductsListView.EditItem == null)
{ ProductsListView.DataSource = LoadDataSet();
ProductsListView.DataBind();
}
}
As you can see we are checking if this is "view mode" or "edit mode" to bind the right data to the ListView control. This will be more clear as we get to the other event handlers. After we call DataBind method ItemDataBound event is fired.
protected void ProductsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
DataRowView drv = (DataRowView)dataItem.DataItem;
if (ProductsListView.EditItem == null)
{
Label companyName = (Label)e.Item.FindControl("CompanyName");
companyName.Text = drv["CompanyName"].ToString();
Label city = (Label)e.Item.FindControl("City");
city.Text = drv["City"].ToString();
Label customerID = (Label)e.Item.FindControl("CustomerID");
customerID.Text = drv["CustomerID"].ToString();
}
... Here we are again checking which template is being rendered, because if we are in "view mode" and we are looking for TextBox controls we will get an error. Now all data from DataSet is bound to Label controls in ItemTemplate and page is rendered. item.JPG Edit button's CommandName attribute is set to "Edit". This is going to fire new event - ItemEditing.
maxi cassolaPosted Apr 11, 2013, 11:55 PM
good!