public void GridViewRowCollection_DefaultPropertyNotWorking ()
		{
			GridViewRowCollection collection = new GridViewRowCollection (new ArrayList ());
			// Note : does not contain a definition for `IsReadOnly'
			//Assert.AreEqual (false, collection.IsReadOnly, "IsReadOnly");		//Always return false
			Assert.AreEqual (collection, collection.SyncRoot, "SyncRoot");
		}
		public void GridViewRowCollection_AssignProperty ()
		{
			ArrayList list = new ArrayList ();
			list.Add(new GridViewRow (0, 0, DataControlRowType.DataRow, DataControlRowState.Normal));
			GridViewRowCollection collection = new GridViewRowCollection (list);
			Assert.AreEqual (1, collection.Count, "Count");
			// Note : does not contain a definition for `IsReadOnly'
			//Assert.AreEqual (false, collection.IsReadOnly, "IsReadOnly");		//Always return false
			Assert.AreEqual (false, collection.IsSynchronized, "IsSynchronized");   //Always return false
			Assert.AreEqual (typeof(GridViewRow), collection[0].GetType (), "Item");
		}
        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (Extender.AdapterEnabled)
            {
                GridView gridView = Control as GridView;
                if (gridView != null)
                {
                    writer.Indent++;
                    WritePagerSection(writer, PagerPosition.Top);

                    writer.WriteLine();
                    writer.WriteBeginTag("table");

                    if (renderTableId)
                    {
                        writer.WriteAttribute("id", "tbl" + gridView.ClientID);
                    }

                    if (tableCssClass.Length > 0)
                    {
                        writer.WriteAttribute("class", tableCssClass);
                    }

                    if (renderCellSpacing)
                    {
                        writer.WriteAttribute("cellspacing", "0");
                    }

                    writer.WriteAttribute("summary", Control.ToolTip);

                    if (!String.IsNullOrEmpty(gridView.CssClass))
                    {
                        writer.WriteAttribute("class", gridView.CssClass);
                    }

                    writer.Write(HtmlTextWriter.TagRightChar);
                    writer.Indent++;

                    ArrayList rows = new ArrayList();
                    GridViewRowCollection gvrc = null;

                    ///////////////////// HEAD /////////////////////////////

                    rows.Clear();
                    if (gridView.ShowHeader && (gridView.HeaderRow != null))
                    {
                        rows.Add(gridView.HeaderRow);
                    }
                    gvrc = new GridViewRowCollection(rows);
                    WriteRows(writer, gridView, gvrc, "thead");

                    ///////////////////// FOOT /////////////////////////////

                    rows.Clear();
                    if (gridView.ShowFooter && (gridView.FooterRow != null))
                    {
                        rows.Add(gridView.FooterRow);
                    }
                    gvrc = new GridViewRowCollection(rows);
                    WriteRows(writer, gridView, gvrc, "tfoot");

                    /////////////// EmptyDataTemplate ///////////////////////
                    // http://stackoverflow.com/questions/3856890/gridview-using-css-friendly-control-adapters-removes-emptydatatemplate-and-empt
                    if (gridView.Rows.Count == 0)
                    {
                        //Control[0].Control[0] s/b the EmptyDataTemplate.
                        if (gridView.HasControls())
                        {
                            if (gridView.Controls[0].HasControls())
                            {
                                if (gridView.Controls[0].Controls[0] is GridViewRow)
                                {
                                    rows.Clear();
                                    rows.Add(gridView.Controls[0].Controls[0]);
                                    gvrc = new GridViewRowCollection(rows);
                                    WriteRows(writer, gridView, gvrc, "tfoot");
                                }
                            }
                        }
                    }

                    ///////////////////// BODY /////////////////////////////

                    WriteRows(writer, gridView, gridView.Rows, "tbody");

                    ////////////////////////////////////////////////////////

                    writer.Indent--;
                    writer.WriteLine();
                    writer.WriteEndTag("table");

                    WritePagerSection(writer, PagerPosition.Bottom);

                    writer.Indent--;
                    writer.WriteLine();
                }
            }
            else
            {
                base.RenderContents(writer);
            }
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (Extender.AdapterEnabled)
            {
                GridView gridView = Control as GridView;
                if (gridView != null)
                {
                    writer.Indent++;
                    WritePagerSection(writer, PagerPosition.Top);

                    writer.WriteLine();
                    writer.WriteBeginTag("table");
                    writer.WriteAttribute("id", gridView.ClientID);
                    writer.WriteAttribute("cellpadding", "0");
                    writer.WriteAttribute("cellspacing", "0");
                    writer.WriteAttribute("summary", Control.ToolTip);
                    writer.Write(HtmlTextWriter.TagRightChar);
                    writer.Indent++;

                    ArrayList rows = new ArrayList();
                    GridViewRowCollection gvrc = null;

                    ///////////////////// HEAD /////////////////////////////

                    rows.Clear();
                    if (gridView.ShowHeader && (gridView.HeaderRow != null))
                    {
                        rows.Add(gridView.HeaderRow);
                    }
                    gvrc = new GridViewRowCollection(rows);
                    WriteRows(writer, gridView, gvrc, "thead");

                    ///////////////////// FOOT /////////////////////////////

                    rows.Clear();
                    if (gridView.ShowFooter && (gridView.FooterRow != null))
                    {
                        rows.Add(gridView.FooterRow);
                    }
                    gvrc = new GridViewRowCollection(rows);
                    WriteRows(writer, gridView, gvrc, "tfoot");

                    ///////////////////// BODY /////////////////////////////

                    WriteRows(writer, gridView, gridView.Rows, "tbody");

                    ////////////////////////////////////////////////////////

                    writer.Indent--;
                    writer.WriteLine();
                    writer.WriteEndTag("table");

					WriteEmptyTextSection(writer);
                    WritePagerSection(writer, PagerPosition.Bottom);

                    writer.Indent--;
                    writer.WriteLine();
                }
            }
            else
            {
                base.RenderContents(writer);
            }
        }
        private void WriteRows(HtmlTextWriter writer, GridView gridView, GridViewRowCollection rows, string tableSection)
        {
            if (rows.Count > 0)
            {
                writer.WriteLine();
                writer.WriteBeginTag(tableSection);
                writer.Write(HtmlTextWriter.TagRightChar);
                writer.Indent++;

                foreach (GridViewRow row in rows)
                {
                    writer.WriteLine();
                    writer.WriteBeginTag("tr");

                    string className = GetRowClass(gridView, row);
                    if (!String.IsNullOrEmpty(className))
                    {
                        writer.WriteAttribute("class", className);
                    }
                    writer.Write(HtmlTextWriter.TagRightChar);
                    writer.Indent++;

                    int i = 0;
                    foreach (TableCell cell in row.Cells)
                    {
                        if (!gridView.Columns[i++].Visible)
                            continue;

                        DataControlFieldCell fieldCell = cell as DataControlFieldCell;

                        if(tableSection == "tbody" && fieldCell != null
                            && (fieldCell.Text.Trim() == "") && fieldCell.Controls.Count == 0)
                            cell.Controls.Add(new LiteralControl("<div style=\"width:1px;height:1px;\">&nbsp;</div>"));
                        else if (tableSection == "thead" && fieldCell != null
                            && !String.IsNullOrEmpty(gridView.SortExpression)
                            && fieldCell.ContainingField.SortExpression == gridView.SortExpression)
                        {
                            cell.Attributes["class"] = "AspNet-GridView-Sort";
                        }

                        if ((fieldCell != null) && (fieldCell.ContainingField != null))
                        {
                            DataControlField field = fieldCell.ContainingField;
                            if (!field.Visible)
                            {
                                cell.Visible = false;
                            }

							if (field.ItemStyle.Width != Unit.Empty)
								cell.Style["width"] = field.ItemStyle.Width.ToString();

							if (!field.ItemStyle.Wrap)
								cell.Style["white-space"] = "nowrap";

                            if ((field.ItemStyle != null) && (!String.IsNullOrEmpty(field.ItemStyle.CssClass)))
                            {
                                if (!String.IsNullOrEmpty(cell.CssClass))
                                {
                                    cell.CssClass += " ";
                                }
                                cell.CssClass += field.ItemStyle.CssClass;
                            }
                        }
                        
                        writer.WriteLine();
                        cell.RenderControl(writer);
                    }

                    writer.Indent--;
                    writer.WriteLine();
                    writer.WriteEndTag("tr");
                }
                
                writer.Indent--;
                writer.WriteLine();
                writer.WriteEndTag(tableSection);
            }
        }
		public void GridViewRowCollection_GetEnumerator ()
		{
			ArrayList list = new ArrayList ();
			list.Add (new GridViewRow (0, 0, DataControlRowType.DataRow, DataControlRowState.Normal));
			GridViewRowCollection collection = new GridViewRowCollection (list);
			IEnumerator numerator = collection.GetEnumerator ();
			Assert.IsNotNull (numerator, "IEnumeratorCreated");
			numerator.Reset ();
			numerator.MoveNext ();
			Assert.AreEqual (numerator.Current, collection[0], "GetEnumeratorCurrent");
			Assert.AreEqual (typeof (GridViewRow), numerator.Current.GetType (), ""); 
		}
		public void GridViewRowCollection_CopyTo ()
		{
			ArrayList list = new ArrayList ();
			list.Add (new GridViewRow (0, 0, DataControlRowType.DataRow, DataControlRowState.Normal));
			GridViewRowCollection collection = new GridViewRowCollection (list);
			GridViewRow[] rows = new GridViewRow[collection.Count];
			collection.CopyTo (rows, 0);
			Assert.AreEqual (collection.Count, rows.Length, "CopyToLenth");
			Assert.IsNotNull (rows[0], "CopyToTargetCreated");
			Assert.AreEqual (collection[0].GetType (), rows[0].GetType (), "CopyToTargetType");
		}
        protected int CreateControlHeirarchy(IEnumerable dataSource, bool useDataSource)
        {
            // Clear/create the rows ArrayList
            if (this._rows == null)
                this._rows = new ArrayList();
            else
                this._rows.Clear();

            GridViewRow hdr = this.BuildHeader();

            if (this.PageIndex < 0)
                this.PageIndex = 0;
            //int startRec = this.PageIndex * this.PageSize;
            int itemCount = 0; //, recCount = 0;
            if (dataSource != null)
            {
                foreach (var dataItem in dataSource)
                {
                    //if (recCount < startRec || itemCount >= this.PageSize)
                    //{
                    //    recCount++;
                    //    continue;
                    //}

                    GridViewRow tr = new GridViewRow(itemCount + (this.ShowHeader ? 1 : 0), itemCount, DataControlRowType.DataRow, (itemCount % 2 == 0 ? DataControlRowState.Normal : DataControlRowState.Alternate));
                    tr.CssClass = (itemCount % 2 == 0) ? "GridViewLineAlt" : "GridViewLine";

                    TableCell tdL = new TableCell();
                    tdL.CssClass = "GridViewLineLeft";
                    tr.Cells.Add(tdL);

                    int curColCount = 0;
                    for (int i = 0; i < this.Columns.Count; i++)
                    {
                        TableCell td = new TableCell();

                        DataControlField column = this.Columns[i];

                        bool usedTemplate = false;
                        if (column is TemplateField)
                        {
                            TemplateField fld = (column as TemplateField);
                            ITemplate template = null;
                            if (itemCount % 2 != 0)
                                template = fld.AlternatingItemTemplate;
                            if (template == null)
                                template = fld.ItemTemplate;

                            if (template != null)
                            {
                                template.InstantiateIn(td);
                                usedTemplate = true;
                            }
                        }

                        if (!usedTemplate)
                        {
                            string dataStr = string.Empty;
                            if (column is BoundField)
                            {
                                BoundField fld = (column as BoundField);
                                if (!string.IsNullOrEmpty(fld.DataField))
                                    dataStr = DataBinder.GetPropertyValue(dataItem, fld.DataField, fld.DataFormatString);
                                else
                                {
                                    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(dataItem);
                                    if (props.Count >= 1)
                                        if (null != props[0].GetValue(dataItem))
                                            dataStr = props[0].GetValue(dataItem).ToString();
                                }
                            }

                            if (column is CheckBoxField)
                            {
                                CheckBoxField fld = (column as CheckBoxField);
                                CheckBox chkFld = new CheckBox();
                                chkFld.ID = string.Format("chkField_{0}_{1}", itemCount, i);
                                string fldStr = string.Empty;
                                if (!string.IsNullOrEmpty(fld.Text))
                                    fldStr = fld.Text;
                                else if (!string.IsNullOrEmpty(fld.DataField))
                                    fldStr = dataStr;
                                chkFld.Text = fldStr;
                                chkFld.MergeStyle(fld.ControlStyle);
                                td.Controls.Add(chkFld);
                            }
                            else if (column is CommandField)
                            {
                                CommandField fld = (column as CommandField);

                                string keyArg = string.Empty;
                                if (this.DataKeyNames != null && this.DataKeyNames.Length > 0)
                                    keyArg = string.Join(",", this.DataKeyNames);

                                if (fld.ShowSelectButton)
                                {
                                    WebControl btn = this.GetButton(fld, "Select", keyArg, itemCount, i, fld.SelectText, fld.SelectImageUrl);
                                    td.Controls.Add(btn);
                                }

                                if (fld.ShowEditButton)
                                {
                                    WebControl btn = this.GetButton(fld, "Edit", keyArg, itemCount, i, fld.EditText, fld.EditImageUrl);
                                    td.Controls.Add(btn);
                                }

                                if (fld.ShowDeleteButton)
                                {
                                    WebControl btn = this.GetButton(fld, "Delete", keyArg, itemCount, i, fld.DeleteText, fld.DeleteImageUrl);
                                    td.Controls.Add(btn);
                                }
                            }
                            else if (column is ButtonField)
                            {
                                ButtonField fld = (column as ButtonField);

                                string keyArg = string.Empty;
                                if (this.DataKeyNames != null && this.DataKeyNames.Length > 0)
                                    keyArg = string.Join(",", this.DataKeyNames);

                                string btnText = dataStr = DataBinder.GetPropertyValue(dataItem, fld.DataTextField, fld.DataTextFormatString);
                                WebControl btn = this.GetButton(fld, fld.CommandName, keyArg, itemCount, i, btnText, fld.ImageUrl);
                                td.Controls.Add(btn);
                            }
                            else
                            {
                                td.Text = dataStr;
                            }
                        }

                        td.MergeStyle(column.ItemStyle);
                        if (curColCount > 0)
                            td.Style.Add("border-left", "solid 1px #ccccd3");
                        curColCount++;
                        tr.Cells.Add(td);
                    }

                    if (this.AutoGenerateColumns)
                    {
                        // If auto-generate columns is set to true, then create a column for each field in the data.
                        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(dataItem);
                        for (int i = 0; i < props.Count; i++)
                        {
                            TableCell td = new TableCell();

                            if (null != props[i].GetValue(dataItem))
                                td.Text = props[i].GetValue(dataItem).ToString();

                            td.MergeStyle(this.ItemStyle);
                            if (curColCount > 0)
                                td.Style.Add("border-left", "solid 1px #ccccd3");
                            curColCount++;
                            tr.Cells.Add(td);
                        }
                    }

                    TableCell tdR = new TableCell();
                    tdR.CssClass = "GridViewLineRight";
                    tr.Cells.Add(tdR);

                    _rows.Add(tr);
                    this.OnItemCreated(new GridViewItemEventArgs(tr));
                    itemCount++;
                }
                //this.TotalRecordCount = recCount;
                //this.PageCount = (int)Math.Ceiling((double)this.TotalRecordCount / (double)this.PageSize);
            }
            this._rowCol = new GridViewRowCollection(this._rows);
            //this.ViewState["!_tblData"] = dataSource;

            GridViewRow ftr = this.BuildFooter();

            //if (this.CacheDuration > 0)
            //{
            //    System.Web.HttpContext.Current.Cache.Remove("GridViewObj" + this.UniqueID);
            //    System.Web.HttpContext.Current.Cache.Insert("GridViewObj" + this.UniqueID, dataSource, null, DateTime.Now.AddMinutes(this.CacheDuration), TimeSpan.Zero);
            //}

            return itemCount;
        }
		public void GridViewRowCollection_DefaultProperty ()
		{
			GridViewRowCollection collection = new GridViewRowCollection(new ArrayList());
			Assert.AreEqual (0, collection.Count, "Count");
			Assert.AreEqual (false, collection.IsSynchronized, "IsSynchronized");   //Always return false
		}
		public void GridViewRowCollection_ItemException ()
		{
			GridViewRowCollection collection = new GridViewRowCollection (new ArrayList ());
			Assert.AreEqual (null, collection[0], "Item");

		}
		/// <summary>
		/// Gets a value indicating whether the specified business object is
		/// currently represented by the <see cref="GridViewRowCollection"/> object.
		/// </summary>
		/// <param name="rows">A <see cref="GridViewRowCollection"/> object.</param>
		/// <param name="link">The current business object.</param>
		/// <returns>True if the specified business object is represented by
		/// the <see cref="GridViewRowCollection"/> object.</returns>
		public bool IsCurrentItem(GridViewRowCollection rows, Object link)
		{
			GridViewRow row = GetRow(rows, link);
			String origValue, currValue;
			bool isCurrent = false;

			if ( row != null )
			{
				isCurrent = true;

				foreach ( EntityProperty property in PropertyMappings )
				{
					if ( property.IsKey )
					{
						/*
						value = GetOriginalValue(row, property.DataField);

						// compare original value
						if ( !EntityUtil.IsPropertyValueEqual(link, property.DataField, value) )
						{
							isCurrent = false;
							break;
						}
						// check for current value, if OriginalValueControlID is used
						if ( !String.IsNullOrEmpty(property.OriginalValueControlID) )
						{
							strValue = String.Format("{0}", GetValue(row, property.DataField));

							if ( String.IsNullOrEmpty(strValue) )
							{
								isCurrent = false;
								break;
							}
						}
						*/

						origValue = String.Format("{0}", GetOriginalValue(row, property.DataField));
						currValue = String.Format("{0}", GetValue(row, property.DataField));

						if ( !String.IsNullOrEmpty(origValue) && String.IsNullOrEmpty(currValue) )
						{
							isCurrent = false;
							break;
						}
					}
				}
			}

			return isCurrent;
		}
		/// <summary>
		/// Gets the current <see cref="GridViewRow"/> object that represents
		/// the specified business object.
		/// </summary>
		/// <param name="rows">A <see cref="GridViewRowCollection"/>.</param>
		/// <param name="link">The current business object.</param>
		/// <returns>A <see cref="GridViewRow"/> object.</returns>
		public GridViewRow GetRow(GridViewRowCollection rows, Object link)
		{
			Object value = EntityUtil.GetPropertyValue(link, ForeignKeyName);
			GridViewRow gridRow = null;

			if ( value != null )
			{
				String strValue = String.Format("{0}", value);
				String id;

				foreach ( GridViewRow row in rows )
				{
					id = GetForeignKeyValue(row) as String;

					if ( strValue.Equals(id) )
					{
						gridRow = row;
						break;
					}
				}
			}

			return gridRow;
		}
        /// <internalonly/>
        /// <devdoc>
        ///    <para>Creates the control hierarchy that is used to render the Smart.
        ///       This is called whenever a control hierarchy is needed and the
        ///       ChildControlsCreated property is false.
        ///       The implementation assumes that all the children in the controls
        ///       collection have already been cleared.</para>
        /// </devdoc>
        protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding) {
            PagedDataSource pagedDataSource = null;

            if (dataBinding) {
                bool allowPaging = AllowPaging;
                DataSourceView view = GetData();
                DataSourceSelectArguments arguments = SelectArguments;
                if (view == null) {
                    throw new HttpException(SR.GetString(SR.DataBoundControl_NullView, ID));
                }

                bool useServerPaging = allowPaging && view.CanPage;

                if (allowPaging && !view.CanPage) {
                    if (dataSource != null && !(dataSource is ICollection)) {
                        arguments.StartRowIndex = checked(PageSize * PageIndex);
                        arguments.MaximumRows = PageSize;
                        // This should throw an exception saying the data source can't page.
                        // We do this because the data source can provide a better error message than we can.
                        view.Select(arguments, SelectCallback);
                    }
                }

                if (useServerPaging) {
                    if (view.CanRetrieveTotalRowCount) {
                        pagedDataSource = CreateServerPagedDataSource(arguments.TotalRowCount);
                    }
                    else {
                        ICollection dataSourceCollection = dataSource as ICollection;
                        if (dataSourceCollection == null) {
                            throw new HttpException(SR.GetString(SR.DataBoundControl_NeedICollectionOrTotalRowCount, GetType().Name));
                        }
                        int priorPagesRecordCount = checked(PageIndex * PageSize);
                        pagedDataSource = CreateServerPagedDataSource(checked(priorPagesRecordCount + dataSourceCollection.Count));
                    }
                }
                else {
                    pagedDataSource = CreatePagedDataSource();
                }
            }
            else {
                pagedDataSource = CreatePagedDataSource();
            }

            IEnumerator pagedDataSourceEnumerator = null;
            int count = 0;
            ArrayList keyArray = DataKeysArrayList;
            ArrayList suffixArray = ClientIDRowSuffixArrayList;
            ICollection fields = null;
            int itemCount = -1; // number of items in the collection.  We need to know to decide if we need a null row.
            int rowsArrayCapacity = 0;
            ICollection collection = dataSource as ICollection;

            if (dataBinding) {
                keyArray.Clear();
                suffixArray.Clear();
                if (dataSource != null) {
                    // If we got to here, it's because the data source view said it could page, but then returned
                    // something that wasn't an ICollection.  Probably a data source control author error.
                    if ((collection == null) && (pagedDataSource.IsPagingEnabled && !pagedDataSource.IsServerPagingEnabled)) {
                        throw new HttpException(SR.GetString(SR.GridView_Missing_VirtualItemCount, ID));
                    }
                }
            }
            else {
                if (collection == null) {
                    throw new HttpException(SR.GetString(SR.DataControls_DataSourceMustBeCollectionWhenNotDataBinding));
                }
            }

            _pageCount = 0;
            if (dataSource != null) {
                pagedDataSource.DataSource = dataSource;
                if (pagedDataSource.IsPagingEnabled && dataBinding) {
                    // Fix up the page index if we have gone past the page count
                    int pagedDataSourcePageCount = pagedDataSource.PageCount;
                    Debug.Assert(pagedDataSource.CurrentPageIndex >= 0);
                    if (pagedDataSource.CurrentPageIndex >= pagedDataSourcePageCount) {
                        int lastPageIndex = pagedDataSourcePageCount - 1;
                        pagedDataSource.CurrentPageIndex = _pageIndex = lastPageIndex;
                    }
                }
                fields = CreateColumns(dataBinding ? pagedDataSource : null, dataBinding);

                if (collection != null) {
                    itemCount = collection.Count;
                    int pageSize = pagedDataSource.IsPagingEnabled ? pagedDataSource.PageSize : collection.Count;
                    rowsArrayCapacity = pageSize;
                    if (dataBinding) {
                        keyArray.Capacity = pageSize;
                        suffixArray.Capacity = pageSize;
                    }
                    // PagedDataSource has strange nehavior here.  If DataSourceCount is 0 but paging is enabled,
                    // it returns a PageCount of 1, which is inconsistent with DetailsView and FormView.
                    // We don't want to change PagedDataSource for back compat reasons.
                    if (pagedDataSource.DataSourceCount == 0) {
                        _pageCount = 0;
                    }
                    else {
                        _pageCount = pagedDataSource.PageCount;
                    }
                }
            }
            _rowsArray = new ArrayList(rowsArrayCapacity);
            _rowsCollection = null;
            _dataKeyArray = null;
            _clientIDRowSuffixArray = null;

            Table table = CreateChildTable();
            Controls.Add(table);

            TableRowCollection rows = table.Rows;

            // 
            if (dataSource == null) {
                if (EmptyDataTemplate != null || EmptyDataText.Length > 0) {
                    CreateRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal, dataBinding, null, new DataControlField[0], rows, null);
                }
                else {
                    Controls.Clear();
                }
                return 0;
            }

            int fieldCount = 0;
            if (fields != null)
                fieldCount = fields.Count;

            DataControlField[] displayFields = new DataControlField[fieldCount];
            if (fieldCount > 0) {
                fields.CopyTo(displayFields, 0);

                bool requiresDataBinding = false;

                for (int c = 0; c < displayFields.Length; c++) {
                    if (displayFields[c].Initialize(AllowSorting, this)) {
                        requiresDataBinding = true;
                    }

                    if (DetermineRenderClientScript()) {
                        displayFields[c].ValidateSupportsCallback();
                    }
                }

                if (requiresDataBinding) {
                    RequiresDataBinding = true;
                }
            }

            GridViewRow row;
            DataControlRowType rowType;
            DataControlRowState rowState;
            int index = 0;
            int dataSourceIndex = 0;

            string[] dataKeyNames = DataKeyNamesInternal;
            bool storeKeys = (dataBinding && (dataKeyNames.Length != 0));
            bool storeSuffix = (dataBinding && ClientIDRowSuffixInternal.Length != 0);
            bool createPager = pagedDataSource.IsPagingEnabled;
            int editIndex = EditIndex;

            if (itemCount == -1) {
                if (_storedDataValid) {
                    if (_firstDataRow != null) {
                        itemCount = 1;
                    }
                    else {
                        itemCount = 0;
                    }
                }
                else {
                    // make sure there's at least one item in the source.
                    IEnumerator e = dataSource.GetEnumerator();

                    if (e.MoveNext()) {
                        object sampleItem = e.Current;
                        StoreEnumerator(e, sampleItem);
                        itemCount = 1;
                    }
                    else {
                        itemCount = 0;
                    }
                }
            }
            if (itemCount == 0) {
                bool controlsCreated = false;

                if (ShowHeader && ShowHeaderWhenEmpty && displayFields.Length > 0) {
                    _headerRow = CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal, dataBinding, null, displayFields, rows, null);
                    controlsCreated = true;
                }
                if (EmptyDataTemplate != null || EmptyDataText.Length > 0) {
                    CreateRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal, dataBinding, null, displayFields, rows, null);
                    controlsCreated = true;
                }

                if (!controlsCreated) {
                    Controls.Clear();
                }
                _storedDataValid = false;
                _firstDataRow = null;
                return 0;
            }

            if (fieldCount > 0) {
                if (pagedDataSource.IsPagingEnabled)
                    dataSourceIndex = pagedDataSource.FirstIndexInPage;

                if (createPager && PagerSettings.Visible && _pagerSettings.IsPagerOnTop) {
                    _topPagerRow = CreateRow(-1, -1, DataControlRowType.Pager, DataControlRowState.Normal, dataBinding, null, displayFields, rows, pagedDataSource);
                }

                _headerRow = CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal, dataBinding, null, displayFields, rows, null);
                if (!ShowHeader) {
                    _headerRow.Visible = false;
                }

                if (storeKeys) {
                    // Reset the selected index if we have a persisted datakey so we
                    // can figure out what index to select based on the key
                    ResetPersistedSelectedIndex();
                }

                if (_storedDataValid) {
                    pagedDataSourceEnumerator = _storedData;
                    if (_firstDataRow != null) {
                        if (storeKeys) {
                            OrderedDictionary keyTable = new OrderedDictionary(dataKeyNames.Length);
                            foreach (string keyName in dataKeyNames) {
                                object keyValue = DataBinder.GetPropertyValue(_firstDataRow, keyName);
                                keyTable.Add(keyName, keyValue);
                            }
                            if (keyArray.Count == index) {
                                keyArray.Add(new DataKey(keyTable, dataKeyNames));
                            }
                            else {
                                keyArray[index] = new DataKey(keyTable, dataKeyNames);
                            }
                        }

                        if (storeSuffix) {
                            OrderedDictionary suffixTable = new OrderedDictionary(ClientIDRowSuffixInternal.Length);
                            foreach (string suffixName in ClientIDRowSuffixInternal) {
                                object suffixValue = DataBinder.GetPropertyValue(_firstDataRow, suffixName);
                                suffixTable.Add(suffixName, suffixValue);
                            }
                            if (suffixArray.Count == index) {
                                suffixArray.Add(new DataKey(suffixTable, ClientIDRowSuffixInternal));
                            }
                            else {
                                suffixArray[index] = new DataKey(suffixTable, ClientIDRowSuffixInternal);
                            }
                        }

                        if (storeKeys && EnablePersistedSelection) {
                            if (index < keyArray.Count) {
                                SetPersistedDataKey(index, (DataKey)keyArray[index]);
                            }
                        }

                        rowType = DataControlRowType.DataRow;
                        rowState = DataControlRowState.Normal;
                        if (index == editIndex)
                            rowState |= DataControlRowState.Edit;
                        if (index == _selectedIndex)
                            rowState |= DataControlRowState.Selected;

                        row = CreateRow(0, dataSourceIndex, rowType, rowState, dataBinding, _firstDataRow, displayFields, rows, null);
                        _rowsArray.Add(row);

                        count++;
                        index++;
                        dataSourceIndex++;

                        _storedDataValid = false;
                        _firstDataRow = null;
                    }
                }
                else {
                    pagedDataSourceEnumerator = pagedDataSource.GetEnumerator();
                }

                rowType = DataControlRowType.DataRow;
                while (pagedDataSourceEnumerator.MoveNext()) {
                    object dataRow = pagedDataSourceEnumerator.Current;

                    if (storeKeys) {
                        OrderedDictionary keyTable = new OrderedDictionary(dataKeyNames.Length);
                        foreach (string keyName in dataKeyNames) {
                            object keyValue = DataBinder.GetPropertyValue(dataRow, keyName);
                            keyTable.Add(keyName, keyValue);
                        }
                        if (keyArray.Count == index) {
                            keyArray.Add(new DataKey(keyTable, dataKeyNames));
                        }
                        else {
                            keyArray[index] = new DataKey(keyTable, dataKeyNames);
                        }
                    }

                    if (storeSuffix) {
                        OrderedDictionary suffixTable = new OrderedDictionary(ClientIDRowSuffixInternal.Length);
                        foreach (string suffixName in ClientIDRowSuffixInternal) {
                            object suffixValue = DataBinder.GetPropertyValue(dataRow, suffixName);
                            suffixTable.Add(suffixName, suffixValue);
                        }
                        if (suffixArray.Count == index) {
                            suffixArray.Add(new DataKey(suffixTable, ClientIDRowSuffixInternal));
                        }
                        else {
                            suffixArray[index] = new DataKey(suffixTable, ClientIDRowSuffixInternal);
                        }
                    }

                    if (storeKeys && EnablePersistedSelection) {
                        if (index < keyArray.Count) {
                            SetPersistedDataKey(index, (DataKey)keyArray[index]);
                        }
                    }

                    rowState = DataControlRowState.Normal;
                    if (index == editIndex)
                        rowState |= DataControlRowState.Edit;
                    if (index == _selectedIndex)
                        rowState |= DataControlRowState.Selected;
                    if (index % 2 != 0) {
                        rowState |= DataControlRowState.Alternate;
                    }

                    row = CreateRow(index, dataSourceIndex, rowType, rowState, dataBinding, dataRow, displayFields, rows, null);
                    _rowsArray.Add(row);

                    count++;
                    dataSourceIndex++;
                    index++;
                }

                if (index == 0) {
                    CreateRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal, dataBinding, null, displayFields, rows, null);
                }

                _footerRow = CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal, dataBinding, null, displayFields, rows, null);
                if (!ShowFooter) {
                    _footerRow.Visible = false;
                }

                if (createPager && PagerSettings.Visible && _pagerSettings.IsPagerOnBottom) {
                    _bottomPagerRow = CreateRow(-1, -1, DataControlRowType.Pager, DataControlRowState.Normal, dataBinding, null, displayFields, rows, pagedDataSource);
                }
            }

            int createdRowsCount = -1;
            if (dataBinding) {
                if (pagedDataSourceEnumerator != null) {
                    if (pagedDataSource.IsPagingEnabled) {
                        _pageCount = pagedDataSource.PageCount;
                        createdRowsCount = pagedDataSource.DataSourceCount;
                    }
                    else {
                        _pageCount = 1;
                        createdRowsCount = count;
                    }
                }
                else {
                    _pageCount = 0;
                }
            }

            if (PageCount == 1) {   // don't show the pager if there's just one row.
                if (_topPagerRow != null) {
                    _topPagerRow.Visible = false;
                }
                if (_bottomPagerRow != null) {
                    _bottomPagerRow.Visible = false;
                }
            }
            return createdRowsCount;

        }
Exemple #14
0
        private void WriteRows(HtmlTextWriter writer, GridView gridView, GridViewRowCollection rows, string tableSection)
        {
            if (rows.Count > 0)
            {
                writer.WriteLine();
                writer.WriteBeginTag(tableSection);
                writer.Write(HtmlTextWriter.TagRightChar);
                writer.Indent++;

                foreach (GridViewRow row in rows)
                {
                    writer.WriteLine();
                    writer.WriteBeginTag("tr");

                    string className = GetRowClass(gridView, row);
                    if (!String.IsNullOrEmpty(className))
                    {
                        writer.WriteAttribute("class", className);
                    }

                    //  Uncomment the following block of code if you want to add arbitrary attributes.
                    foreach (string key in row.Attributes.Keys)
                    {
                        writer.WriteAttribute(key, row.Attributes[key]);
                    }

                    writer.Write(HtmlTextWriter.TagRightChar);
                    writer.Indent++;

                    foreach (TableCell cell in row.Cells)
                    {
                        DataControlFieldCell fieldCell = cell as DataControlFieldCell;
                        if ((fieldCell != null) && (fieldCell.ContainingField != null))
                        {
                            DataControlField field = fieldCell.ContainingField;
                            if (!field.Visible)
                            {
                                cell.Visible = false;
                            }

                            if (field.ItemStyle != null) {

                                if (!string.IsNullOrEmpty(field.ItemStyle.CssClass)) {
                                    if (!String.IsNullOrEmpty(cell.CssClass)) {
                                        cell.CssClass += " ";
                                    }
                                    cell.CssClass += field.ItemStyle.CssClass;
                                }

                                if (!field.ItemStyle.Width.IsEmpty) {
                                    cell.Width = field.ItemStyle.Width;
                                }
                            }

                        }

                        writer.WriteLine();
                        cell.RenderControl(writer);
                    }

                    writer.Indent--;
                    writer.WriteLine();
                    writer.WriteEndTag("tr");
                }

                writer.Indent--;
                writer.WriteLine();
                writer.WriteEndTag(tableSection);
            }
        }
        protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
        {
            PagedDataSource pagedDataSource = null;
            if (dataBinding)
            {
                bool allowPaging = this.AllowPaging;
                DataSourceView data = this.GetData();
                DataSourceSelectArguments selectArguments = base.SelectArguments;
                if (data == null)
                {
                    throw new HttpException(System.Web.SR.GetString("DataBoundControl_NullView", new object[] { this.ID }));
                }
                bool flag2 = allowPaging && data.CanPage;
                if ((allowPaging && !data.CanPage) && ((dataSource != null) && !(dataSource is ICollection)))
                {
                    selectArguments.StartRowIndex = this.PageSize * this.PageIndex;
                    selectArguments.MaximumRows = this.PageSize;
                    data.Select(selectArguments, new DataSourceViewSelectCallback(this.SelectCallback));
                }
                if (flag2)
                {
                    if (data.CanRetrieveTotalRowCount)
                    {
                        pagedDataSource = this.CreateServerPagedDataSource(selectArguments.TotalRowCount);
                    }
                    else
                    {
                        ICollection is2 = dataSource as ICollection;
                        if (is2 == null)
                        {
                            throw new HttpException(System.Web.SR.GetString("DataBoundControl_NeedICollectionOrTotalRowCount", new object[] { base.GetType().Name }));
                        }
                        int num = this.PageIndex * this.PageSize;
                        pagedDataSource = this.CreateServerPagedDataSource(num + is2.Count);
                    }
                }
                else
                {
                    pagedDataSource = this.CreatePagedDataSource();
                }
            }
            else
            {
                pagedDataSource = this.CreatePagedDataSource();
            }
            IEnumerator enumerator = null;
            int num2 = 0;
            ArrayList dataKeysArrayList = this.DataKeysArrayList;
            ArrayList clientIDRowSuffixArrayList = this.ClientIDRowSuffixArrayList;
            ICollection is3 = null;
            int count = -1;
            int capacity = 0;
            ICollection is4 = dataSource as ICollection;
            if (dataBinding)
            {
                dataKeysArrayList.Clear();
                clientIDRowSuffixArrayList.Clear();
                if (((dataSource != null) && (is4 == null)) && (pagedDataSource.IsPagingEnabled && !pagedDataSource.IsServerPagingEnabled))
                {
                    throw new HttpException(System.Web.SR.GetString("GridView_Missing_VirtualItemCount", new object[] { this.ID }));
                }
            }
            else if (is4 == null)
            {
                throw new HttpException(System.Web.SR.GetString("DataControls_DataSourceMustBeCollectionWhenNotDataBinding"));
            }
            this._pageCount = 0;
            if (dataSource != null)
            {
                pagedDataSource.DataSource = dataSource;
                if (pagedDataSource.IsPagingEnabled && dataBinding)
                {
                    int pageCount = pagedDataSource.PageCount;
                    if (pagedDataSource.CurrentPageIndex >= pageCount)
                    {
                        int num6 = pageCount - 1;
                        pagedDataSource.CurrentPageIndex = this._pageIndex = num6;
                    }
                }
                is3 = this.CreateColumns(dataBinding ? pagedDataSource : null, dataBinding);
                if (is4 != null)
                {
                    count = is4.Count;
                    int num7 = pagedDataSource.IsPagingEnabled ? pagedDataSource.PageSize : is4.Count;
                    capacity = num7;
                    if (dataBinding)
                    {
                        dataKeysArrayList.Capacity = num7;
                        clientIDRowSuffixArrayList.Capacity = num7;
                    }
                    if (pagedDataSource.DataSourceCount == 0)
                    {
                        this._pageCount = 0;
                    }
                    else
                    {
                        this._pageCount = pagedDataSource.PageCount;
                    }
                }
            }
            this._rowsArray = new ArrayList(capacity);
            this._rowsCollection = null;
            this._dataKeyArray = null;
            this._clientIDRowSuffixArray = null;
            Table child = this.CreateChildTable();
            this.Controls.Add(child);
            TableRowCollection rows = child.Rows;
            if (dataSource == null)
            {
                if ((this.EmptyDataTemplate != null) || (this.EmptyDataText.Length > 0))
                {
                    this.CreateRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal, dataBinding, null, new DataControlField[0], rows, null);
                }
                else
                {
                    this.Controls.Clear();
                }
                return 0;
            }
            int num8 = 0;
            if (is3 != null)
            {
                num8 = is3.Count;
            }
            DataControlField[] array = new DataControlField[num8];
            if (num8 > 0)
            {
                is3.CopyTo(array, 0);
                bool flag3 = false;
                for (int i = 0; i < array.Length; i++)
                {
                    if (array[i].Initialize(this.AllowSorting, this))
                    {
                        flag3 = true;
                    }
                    if (this.DetermineRenderClientScript())
                    {
                        array[i].ValidateSupportsCallback();
                    }
                }
                if (flag3)
                {
                    base.RequiresDataBinding = true;
                }
            }
            int dataItemIndex = 0;
            int dataSourceIndex = 0;
            string[] dataKeyNamesInternal = this.DataKeyNamesInternal;
            bool flag4 = dataBinding && (dataKeyNamesInternal.Length != 0);
            bool flag5 = dataBinding && (this.ClientIDRowSuffixInternal.Length != 0);
            bool isPagingEnabled = pagedDataSource.IsPagingEnabled;
            int editIndex = this.EditIndex;
            switch (count)
            {
                case -1:
                    if (this._storedDataValid)
                    {
                        if (this._firstDataRow != null)
                        {
                            count = 1;
                        }
                        else
                        {
                            count = 0;
                        }
                    }
                    else
                    {
                        IEnumerator enumerator2 = dataSource.GetEnumerator();
                        if (enumerator2.MoveNext())
                        {
                            object current = enumerator2.Current;
                            this.StoreEnumerator(enumerator2, current);
                            count = 1;
                        }
                        else
                        {
                            count = 0;
                        }
                    }
                    break;

                case 0:
                {
                    bool flag7 = false;
                    if ((this.ShowHeader && this.ShowHeaderWhenEmpty) && (array.Length > 0))
                    {
                        this._headerRow = this.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal, dataBinding, null, array, rows, null);
                        flag7 = true;
                    }
                    if ((this.EmptyDataTemplate != null) || (this.EmptyDataText.Length > 0))
                    {
                        this.CreateRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal, dataBinding, null, array, rows, null);
                        flag7 = true;
                    }
                    if (!flag7)
                    {
                        this.Controls.Clear();
                    }
                    this._storedDataValid = false;
                    this._firstDataRow = null;
                    return 0;
                }
            }
            if (num8 > 0)
            {
                GridViewRow row;
                DataControlRowType dataRow;
                DataControlRowState normal;
                if (pagedDataSource.IsPagingEnabled)
                {
                    dataSourceIndex = pagedDataSource.FirstIndexInPage;
                }
                if ((isPagingEnabled && this.PagerSettings.Visible) && this._pagerSettings.IsPagerOnTop)
                {
                    this._topPagerRow = this.CreateRow(-1, -1, DataControlRowType.Pager, DataControlRowState.Normal, dataBinding, null, array, rows, pagedDataSource);
                }
                this._headerRow = this.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal, dataBinding, null, array, rows, null);
                if (!this.ShowHeader)
                {
                    this._headerRow.Visible = false;
                }
                if (flag4)
                {
                    this.ResetPersistedSelectedIndex();
                }
                if (this._storedDataValid)
                {
                    enumerator = this._storedData;
                    if (this._firstDataRow != null)
                    {
                        if (flag4)
                        {
                            OrderedDictionary keyTable = new OrderedDictionary(dataKeyNamesInternal.Length);
                            foreach (string str in dataKeyNamesInternal)
                            {
                                object propertyValue = DataBinder.GetPropertyValue(this._firstDataRow, str);
                                keyTable.Add(str, propertyValue);
                            }
                            if (dataKeysArrayList.Count == dataItemIndex)
                            {
                                dataKeysArrayList.Add(new DataKey(keyTable, dataKeyNamesInternal));
                            }
                            else
                            {
                                dataKeysArrayList[dataItemIndex] = new DataKey(keyTable, dataKeyNamesInternal);
                            }
                        }
                        if (flag5)
                        {
                            OrderedDictionary dictionary2 = new OrderedDictionary(this.ClientIDRowSuffixInternal.Length);
                            foreach (string str2 in this.ClientIDRowSuffixInternal)
                            {
                                object obj4 = DataBinder.GetPropertyValue(this._firstDataRow, str2);
                                dictionary2.Add(str2, obj4);
                            }
                            if (clientIDRowSuffixArrayList.Count == dataItemIndex)
                            {
                                clientIDRowSuffixArrayList.Add(new DataKey(dictionary2, this.ClientIDRowSuffixInternal));
                            }
                            else
                            {
                                clientIDRowSuffixArrayList[dataItemIndex] = new DataKey(dictionary2, this.ClientIDRowSuffixInternal);
                            }
                        }
                        if ((flag4 && this.EnablePersistedSelection) && (dataItemIndex < dataKeysArrayList.Count))
                        {
                            this.SetPersistedDataKey(dataItemIndex, (DataKey) dataKeysArrayList[dataItemIndex]);
                        }
                        dataRow = DataControlRowType.DataRow;
                        normal = DataControlRowState.Normal;
                        if (dataItemIndex == editIndex)
                        {
                            normal |= DataControlRowState.Edit;
                        }
                        if (dataItemIndex == this._selectedIndex)
                        {
                            normal |= DataControlRowState.Selected;
                        }
                        row = this.CreateRow(0, dataSourceIndex, dataRow, normal, dataBinding, this._firstDataRow, array, rows, null);
                        this._rowsArray.Add(row);
                        num2++;
                        dataItemIndex++;
                        dataSourceIndex++;
                        this._storedDataValid = false;
                        this._firstDataRow = null;
                    }
                }
                else
                {
                    enumerator = pagedDataSource.GetEnumerator();
                }
                dataRow = DataControlRowType.DataRow;
                while (enumerator.MoveNext())
                {
                    object container = enumerator.Current;
                    if (flag4)
                    {
                        OrderedDictionary dictionary3 = new OrderedDictionary(dataKeyNamesInternal.Length);
                        foreach (string str3 in dataKeyNamesInternal)
                        {
                            object obj6 = DataBinder.GetPropertyValue(container, str3);
                            dictionary3.Add(str3, obj6);
                        }
                        if (dataKeysArrayList.Count == dataItemIndex)
                        {
                            dataKeysArrayList.Add(new DataKey(dictionary3, dataKeyNamesInternal));
                        }
                        else
                        {
                            dataKeysArrayList[dataItemIndex] = new DataKey(dictionary3, dataKeyNamesInternal);
                        }
                    }
                    if (flag5)
                    {
                        OrderedDictionary dictionary4 = new OrderedDictionary(this.ClientIDRowSuffixInternal.Length);
                        foreach (string str4 in this.ClientIDRowSuffixInternal)
                        {
                            object obj7 = DataBinder.GetPropertyValue(container, str4);
                            dictionary4.Add(str4, obj7);
                        }
                        if (clientIDRowSuffixArrayList.Count == dataItemIndex)
                        {
                            clientIDRowSuffixArrayList.Add(new DataKey(dictionary4, this.ClientIDRowSuffixInternal));
                        }
                        else
                        {
                            clientIDRowSuffixArrayList[dataItemIndex] = new DataKey(dictionary4, this.ClientIDRowSuffixInternal);
                        }
                    }
                    if ((flag4 && this.EnablePersistedSelection) && (dataItemIndex < dataKeysArrayList.Count))
                    {
                        this.SetPersistedDataKey(dataItemIndex, (DataKey) dataKeysArrayList[dataItemIndex]);
                    }
                    normal = DataControlRowState.Normal;
                    if (dataItemIndex == editIndex)
                    {
                        normal |= DataControlRowState.Edit;
                    }
                    if (dataItemIndex == this._selectedIndex)
                    {
                        normal |= DataControlRowState.Selected;
                    }
                    if ((dataItemIndex % 2) != 0)
                    {
                        normal |= DataControlRowState.Alternate;
                    }
                    row = this.CreateRow(dataItemIndex, dataSourceIndex, dataRow, normal, dataBinding, container, array, rows, null);
                    this._rowsArray.Add(row);
                    num2++;
                    dataSourceIndex++;
                    dataItemIndex++;
                }
                if (dataItemIndex == 0)
                {
                    this.CreateRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal, dataBinding, null, array, rows, null);
                }
                this._footerRow = this.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal, dataBinding, null, array, rows, null);
                if (!this.ShowFooter)
                {
                    this._footerRow.Visible = false;
                }
                if ((isPagingEnabled && this.PagerSettings.Visible) && this._pagerSettings.IsPagerOnBottom)
                {
                    this._bottomPagerRow = this.CreateRow(-1, -1, DataControlRowType.Pager, DataControlRowState.Normal, dataBinding, null, array, rows, pagedDataSource);
                }
            }
            int dataSourceCount = -1;
            if (dataBinding)
            {
                if (enumerator != null)
                {
                    if (pagedDataSource.IsPagingEnabled)
                    {
                        this._pageCount = pagedDataSource.PageCount;
                        dataSourceCount = pagedDataSource.DataSourceCount;
                    }
                    else
                    {
                        this._pageCount = 1;
                        dataSourceCount = num2;
                    }
                }
                else
                {
                    this._pageCount = 0;
                }
            }
            if (this.PageCount == 1)
            {
                if (this._topPagerRow != null)
                {
                    this._topPagerRow.Visible = false;
                }
                if (this._bottomPagerRow != null)
                {
                    this._bottomPagerRow.Visible = false;
                }
            }
            return dataSourceCount;
        }
        private void WriteRows(HtmlTextWriter writer, GridView gridView, GridViewRowCollection rows, string tableSection)
        {
            if (rows.Count > 0)
            {
                writer.WriteLine();
                writer.WriteBeginTag(tableSection);
                writer.Write(HtmlTextWriter.TagRightChar);
                writer.Indent++;

                foreach (GridViewRow row in rows)
                {
                    if (!row.Visible)
                        continue;

                    writer.WriteLine();
                    writer.WriteBeginTag("tr");

                    string className = GetRowClass(gridView, row);
                    if (!String.IsNullOrEmpty(className))
                    {
                        writer.WriteAttribute("class", className);
                    }

                    //  Uncomment the following block of code if you want to add arbitrary attributes.
                    /*
                    foreach (string key in row.Attributes.Keys)
                    {
                            writer.WriteAttribute(key, row.Attributes[key]);
                    }
                    */

                    writer.Write(HtmlTextWriter.TagRightChar);
                    writer.Indent++;

                    foreach (TableCell cell in row.Cells)
                    {
                        DataControlFieldCell fieldCell = cell as DataControlFieldCell;
                        if ((fieldCell != null) && (fieldCell.ContainingField != null))
                        {
                            DataControlField field = fieldCell.ContainingField;
                            if (!field.Visible)
                            {
                                cell.Visible = false;
                            }

                            // Apply item style CSS class
                            TableItemStyle itemStyle;
                            switch (row.RowType)
                            {
                                case DataControlRowType.Header:
                                    itemStyle = field.HeaderStyle;
                                    break;
                                case DataControlRowType.Footer:
                                    itemStyle = field.FooterStyle;
                                    break;
                                default:
                                    itemStyle = field.ItemStyle;
                                    break;
                            }
                            if (itemStyle != null && !String.IsNullOrEmpty(itemStyle.CssClass))
                            {
                                if (!String.IsNullOrEmpty(cell.CssClass))
                                    cell.CssClass += " ";
                                cell.CssClass += itemStyle.CssClass;
                            }
                        }

                        writer.WriteLine();
                        cell.RenderControl(writer);
                    }

                    writer.Indent--;
                    writer.WriteLine();
                    writer.WriteEndTag("tr");
                }

                writer.Indent--;
                writer.WriteLine();
                writer.WriteEndTag(tableSection);
            }
        }
		protected override int CreateChildControls (IEnumerable data, bool dataBinding)
		{
			// clear GridView
			Controls.Clear ();
			table = null;
			rows = null;

			if (data == null) {
				return 0;
			}

			PagedDataSource dataSource;

			if (dataBinding) {
				DataSourceView view = GetData ();
				dataSource = new PagedDataSource ();
				dataSource.DataSource = data;
				
				if (AllowPaging) {
					dataSource.AllowPaging = true;
					dataSource.PageSize = PageSize;
					if (view.CanPage) {
						dataSource.AllowServerPaging = true;
						if (SelectArguments.RetrieveTotalRowCount)
							dataSource.VirtualCount = SelectArguments.TotalRowCount;
					}
					if (PageIndex >= dataSource.PageCount)
						pageIndex = dataSource.PageCount - 1;
					dataSource.CurrentPageIndex = PageIndex;
				}
				
				PageCount = dataSource.PageCount;
			}
			else
			{
				dataSource = new PagedDataSource ();
				dataSource.DataSource = data;
				if (AllowPaging) {
					dataSource.AllowPaging = true;
					dataSource.PageSize = PageSize;
					dataSource.CurrentPageIndex = PageIndex;
				}
			}

			bool createPager = AllowPaging && (PageCount >= 1) && PagerSettings.Visible;

			ArrayList list = new ArrayList ();
			
			// Creates the set of fields to show

			_dataEnumerator = null;
			ICollection fieldCollection = CreateColumns (dataSource, dataBinding);
			int fieldCount = fieldCollection.Count;
			DataControlField dcf;
			DataControlField[] fields = new DataControlField [fieldCount];
			fieldCollection.CopyTo (fields, 0);
			
			for (int i = 0; i < fieldCount; i++) {
				dcf = fields [i];
				dcf.Initialize (AllowSorting, this);
				if (EnableSortingAndPagingCallbacks)
					dcf.ValidateSupportsCallback ();
			}

			bool skip_first = false;
			IEnumerator enumerator;
			if (_dataEnumerator != null) {
				// replaced when creating bound columns
				enumerator = _dataEnumerator;
				skip_first = true;
			}
			else {
				enumerator = dataSource.GetEnumerator ();
			}

			// Main table creation
			while (skip_first || enumerator.MoveNext ()) {
				skip_first = false;
				object obj = enumerator.Current;
				
				if (list.Count == 0) {
					if (createPager && (PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom)) {
						topPagerRow = CreatePagerRow (fieldCount, dataSource);
						OnRowCreated (new GridViewRowEventArgs (topPagerRow));
						ContainedTable.Rows.Add (topPagerRow);
						if (dataBinding) {
							topPagerRow.DataBind ();
							OnRowDataBound (new GridViewRowEventArgs (topPagerRow));
						}
						if (PageCount == 1)
							topPagerRow.Visible = false;
					}

					GridViewRow headerRow = CreateRow (-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
					InitializeRow (headerRow, fields);
					OnRowCreated (new GridViewRowEventArgs (headerRow));
					ContainedTable.Rows.Add (headerRow);
					if (dataBinding) {
						headerRow.DataBind ();
						OnRowDataBound (new GridViewRowEventArgs (headerRow));
					}
				}
				
				DataControlRowState rstate = GetRowState (list.Count);
				GridViewRow row = CreateRow (list.Count, list.Count, DataControlRowType.DataRow, rstate);
				row.DataItem = obj;
				list.Add (row);
				InitializeRow (row, fields);
				OnRowCreated (new GridViewRowEventArgs (row));
				ContainedTable.Rows.Add (row);
				if (dataBinding) {
					row.DataBind ();					
					if (EditIndex == row.RowIndex)
						oldEditValues = new DataKey (GetRowValues (row, true, true));
					DataKeyArrayList.Add (new DataKey (CreateRowDataKey (row), DataKeyNames));
					OnRowDataBound (new GridViewRowEventArgs (row));
				} 
			}

			if (list.Count == 0) {
				GridViewRow emptyRow = CreateEmptyrRow (fieldCount);
				if (emptyRow != null) {
					OnRowCreated (new GridViewRowEventArgs (emptyRow));
					ContainedTable.Rows.Add (emptyRow);
					if (dataBinding) {
						emptyRow.DataBind ();
						OnRowDataBound (new GridViewRowEventArgs (emptyRow));
					}
				}
				return 0;
			}
			else {
				GridViewRow footerRow = CreateRow (-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
				InitializeRow (footerRow, fields);
				OnRowCreated (new GridViewRowEventArgs (footerRow));
				ContainedTable.Rows.Add (footerRow);
				if (dataBinding) {
					footerRow.DataBind ();
					OnRowDataBound (new GridViewRowEventArgs (footerRow));
				}

				if (createPager && (PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom)) {
					bottomPagerRow = CreatePagerRow (fieldCount, dataSource);
					OnRowCreated (new GridViewRowEventArgs (bottomPagerRow));
					ContainedTable.Rows.Add (bottomPagerRow);
					if (dataBinding) {
						bottomPagerRow.DataBind ();
						OnRowDataBound (new GridViewRowEventArgs (bottomPagerRow));
					}
					if (PageCount == 1)
						bottomPagerRow.Visible = false;
				}
			}

			rows = new GridViewRowCollection (list);

			if (!dataBinding)
				return -1;

			if (AllowPaging)
				return dataSource.DataSourceCount;
			else
				return list.Count;
		}
		protected override int CreateChildControls (IEnumerable data, bool dataBinding)
		{
			PagedDataSource dataSource;

			if (dataBinding) {
				DataSourceView view = GetData ();
				dataSource = new PagedDataSource ();
				dataSource.DataSource = data;
				
				if (AllowPaging) {
					dataSource.AllowPaging = true;
					dataSource.PageSize = PageSize;
					dataSource.CurrentPageIndex = PageIndex;
					if (view.CanPage) {
						dataSource.AllowServerPaging = true;
						if (view.CanRetrieveTotalRowCount)
							dataSource.VirtualCount = SelectArguments.TotalRowCount;
						else {
							dataSource.DataSourceView = view;
							dataSource.DataSourceSelectArguments = SelectArguments;
							dataSource.SetItemCountFromPageIndex (PageIndex + PagerSettings.PageButtonCount);
						}
					}
				}
				
				pageCount = dataSource.PageCount;
			}
			else
			{
				dataSource = new PagedDataSource ();
				dataSource.DataSource = data;
				if (AllowPaging) {
					dataSource.AllowPaging = true;
					dataSource.PageSize = PageSize;
					dataSource.CurrentPageIndex = PageIndex;
				}
			}

			bool showPager = AllowPaging && (PageCount > 1);
			
			Controls.Clear ();
			table = CreateChildTable ();
			Controls.Add (table);
				
			ArrayList list = new ArrayList ();
			ArrayList keyList = new ArrayList ();
			
			// Creates the set of fields to show
			
			ICollection fieldCollection = CreateColumns (dataSource, dataBinding);
			DataControlField[] fields = new DataControlField [fieldCollection.Count];
			fieldCollection.CopyTo (fields, 0);

			foreach (DataControlField field in fields) {
				field.Initialize (AllowSorting, this);
				if (EnableSortingAndPagingCallbacks)
					field.ValidateSupportsCallback ();
			}

			// Main table creation
			
			if (showPager && PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom) {
				topPagerRow = CreatePagerRow (fields.Length, dataSource);
				table.Rows.Add (topPagerRow);
			}

			if (ShowHeader) {
				headerRow = CreateRow (0, 0, DataControlRowType.Header, DataControlRowState.Normal);
				table.Rows.Add (headerRow);
				InitializeRow (headerRow, fields);
			}
			
			foreach (object obj in dataSource) {
				DataControlRowState rstate = GetRowState (list.Count);
				GridViewRow row = CreateRow (list.Count, list.Count, DataControlRowType.DataRow, rstate);
				row.DataItem = obj;
				list.Add (row);
				table.Rows.Add (row);
				InitializeRow (row, fields);
				if (dataBinding) {
//					row.DataBind ();
					OnRowDataBound (new GridViewRowEventArgs (row));
					if (EditIndex == row.RowIndex)
						oldEditValues = new DataKey (GetRowValues (row, false, true));
					keyList.Add (new DataKey (CreateRowDataKey (row), DataKeyNames));
				} else {
					if (EditIndex == row.RowIndex)
						oldEditValues = new DataKey (new OrderedDictionary ());
					keyList.Add (new DataKey (new OrderedDictionary (), DataKeyNames));
				}

				if (list.Count >= PageSize)
					break;
			}
			
			if (list.Count == 0)
				table.Rows.Add (CreateEmptyrRow (fields.Length));

			if (ShowFooter) {
				footerRow = CreateRow (0, 0, DataControlRowType.Footer, DataControlRowState.Normal);
				table.Rows.Add (footerRow);
				InitializeRow (footerRow, fields);
			}

			if (showPager && PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom) {
				bottomPagerRow = CreatePagerRow (fields.Length, dataSource);
				table.Rows.Add (bottomPagerRow);
			}

			rows = new GridViewRowCollection (list);
			keys = new DataKeyArray (keyList);
			
			if (dataBinding)
				DataBind (false);

			return dataSource.DataSourceCount;
		}