Telerik blogs
If you have a GridView, DataGrid, DetailsView, FormView, DataList or Repeater bound using DataSourceID you should never touch the controls collection in Page_Init or Page_PreInit. If you do this your declarative data-binding will be lost on any outside of the control post-back.

How to check this?


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">
        <asp:Button ID="Button1" Text="Button1" runat="server" />
        <asp:GridView ID="GridView1" AllowPaging="true" DataSourceID="AccessDataSource1"
        <asp:DetailsView ID="DetailsView1" DataSourceID="AccessDataSource1" AllowPaging="true"
        <asp:FormView ID="FormView1" DataSourceID="AccessDataSource1" AllowPaging="true"
                ProductID :
                <%# Eval("ProductID") %>
        <asp:DataList ID="DataList1" DataSourceID="AccessDataSource1" runat="server">
                ProductID :
                <%# Eval("ProductID") %>
        <asp:Repeater ID="Repeater1" DataSourceID="AccessDataSource1" runat="server">
                ProductID :
                <%# Eval("ProductID") %>
        <asp:DropDownList ID="DropDownList1" DataSourceID="AccessDataSource1" DataValueField="ProductID" runat="server"></asp:DropDownList>
        <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/Nwind.mdb"
            SelectCommand="SELECT TOP 5 * FROM [Products]"></asp:AccessDataSource>

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
    protected void Page_Init(object sender, EventArgs e)
        ControlCollection ControlCollection1 = GridView1.Controls;
        ControlCollection ControlCollection2 = DetailsView1.Controls;
        ControlCollection ControlCollection3 = FormView1.Controls;
        ControlCollection ControlCollection4 = DataList1.Controls;
        ControlCollection ControlCollection5 = Repeater1.Controls;
        ControlCollection ControlCollection6 = DropDownList1.Controls;

... however you can do the same with DropDownList and ListBox controls and ... there will be no problems.

If you want more fun you can use the Reflector to check what is going on :-) ... but never do this in your real application!

About the Author

Vladimir Enchev

is Director of Engineering, Native Mobile UI & Frameworks


Comments are disabled in preview mode.