Avatar of immtrac
immtrac asked on

Adding Columns and Rows dynamically in GridView

I need some serious help here.

I have a Grid View in ascx file. Simple Like this:

<asp:GridView ID="grdFamily" runat="server">

</asp:GridView>

First:

I need to add columns dynamically to this GridView. I am pulling how many and what columns I need from table.

e.g  A         B             C           D          E          F

Second.
Then I need to add rows filled with control under these columns.
Again I have a table from which I will be pulling what type of control are these. Then I need to bind these controls.

e.g 1 mean text box, 2 means drop down etc.

e.g. I need to fill drop down list with data



Third.
Then I need to bind the GridView with a dataset.

------------------In simple, every thing is dynamic.

Can you please help me?
ASP.NET

Avatar of undefined
Last Comment
Member_2_2556239

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Sammy

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
immtrac

The like you provided is in C#. I am looking for code sample in VB. Not sure what you mean by doing  it backwards?
ASKER
immtrac

I am trying to conver the code in VB. But I am getting an error.

 Class 'DynamicTemplate' must implement 'Sub InstantiateIn(container As Control)' for interface 'System.Web.UI.ITemplate'.


Can you help what is wrong with code?
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.ComponentModel
Imports System.Collections
''' <summary>
''' Summary description for DynamicTemplate
''' </summary>
Public Class DynamicTemplate
    Implements System.Web.UI.ITemplate
 
    Private templateType As System.Web.UI.WebControls.ListItemType
    Private htControls As New System.Collections.Hashtable()
    Private htBindPropertiesNames As New System.Collections.Hashtable()
    Private htBindExpression As New System.Collections.Hashtable()
 
    Public Sub New(ByVal type As System.Web.UI.WebControls.ListItemType)
        templateType = type
    End Sub
 
    Public Sub AddControl(ByVal wbControl As WebControl, ByVal BindPropertyName As String, ByVal BindExpression As String)
        htControls.Add(htControls.Count, wbControl)
        htBindPropertiesNames.Add(htBindPropertiesNames.Count, BindPropertyName)
        htBindExpression.Add(htBindExpression.Count, BindExpression)
 
    End Sub
 
    Public Sub InstantiateIn(ByVal container As System.Web.UI.Control)
        Dim ph As New PlaceHolder()
        For i As Integer = 0 To htControls.Count - 1
 
 
            'clone control 
            Dim cntrl As Control = CloneControl(DirectCast(htControls(i), Control))
 
            Select Case templateType
                Case ListItemType.Header
                    Exit Select
                Case ListItemType.Item
                    ph.Controls.Add(cntrl)
                    Exit Select
                Case ListItemType.AlternatingItem
                    ph.Controls.Add(cntrl)
                    AddHandler ph.DataBinding, AddressOf Item_DataBinding
                    Exit Select
                Case ListItemType.Footer
                    Exit Select
            End Select
        Next
        AddHandler ph.DataBinding, AddressOf Item_DataBinding
 
        container.Controls.Add(ph)
 
    End Sub
    Public Sub Item_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim ph As PlaceHolder = DirectCast(sender, PlaceHolder)
        Dim ri As GridViewRow = DirectCast(ph.NamingContainer, GridViewRow)
        For i As Integer = 0 To htControls.Count - 1
            If htBindPropertiesNames(i).ToString().Length > 0 Then
                Dim tmpCtrl As Control = DirectCast(htControls(i), Control)
                Dim item1Value As String = DirectCast(DataBinder.Eval(ri.DataItem, htBindExpression(i).ToString()), String)
                Dim ctrl As Control = ph.FindControl(tmpCtrl.ID)
                Dim t As Type = ctrl.[GetType]()
                Dim pi As System.Reflection.PropertyInfo = t.GetProperty(htBindPropertiesNames(i).ToString())
 
                pi.SetValue(ctrl, item1Value.ToString(), Nothing)
 
            End If
        Next
 
 
 
    End Sub
 
    Private Function CloneControl(ByVal src_ctl As System.Web.UI.Control) As Control
        Dim t As Type = src_ctl.[GetType]()
        Dim obj As Object = Activator.CreateInstance(t)
        Dim dst_ctl As Control = DirectCast(obj, Control)
        Dim src_pdc As PropertyDescriptorCollection = TypeDescriptor.GetProperties(src_ctl)
        Dim dst_pdc As PropertyDescriptorCollection = TypeDescriptor.GetProperties(dst_ctl)
        For i As Integer = 0 To src_pdc.Count - 1
 
 
            If src_pdc(i).Attributes.Contains(DesignerSerializationVisibilityAttribute.Content) Then
 
                Dim collection_val As Object = src_pdc(i).GetValue(src_ctl)
                If (TypeOf collection_val Is IList) = True Then
                    For Each child As Object In DirectCast(collection_val, IList)
                        Dim new_child As Control = CloneControl(TryCast(child, Control))
                        Dim dst_collection_val As Object = dst_pdc(i).GetValue(dst_ctl)
                        DirectCast(dst_collection_val, IList).Add(new_child)
                    Next
                End If
            Else
                dst_pdc(src_pdc(i).Name).SetValue(dst_ctl, src_pdc(i).GetValue(src_ctl))
            End If
        Next
 
        Return dst_ctl
 
    End Function
End Class

Open in new window

Sammy

implementation  in VB.Net is a little out of whack


Public Class DynamicTemplate
 : Implements System.Web.UI.ITemplate
    Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
'do implementation here
    End Sub
End Class

Open in new window

Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Member_2_2556239

Has anyone got this to work inside an ascx? It works for me on first load of the grid, afte a postback the template column disappears (is left empty).
Tom Knowlton

beheer:

See if this code can help you.  This code is from an ASCX where I add the columns for the GridView programmatically.  Notice no columns are defined in the HTML Markup.  This code even supports a checkbox on the left hand side.

It's a little buggy...but should be enough to get you started.

See the snippet:
CODE BEHIND:
 
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
 
//Most stable version to date.  CHECK ALL functionality is working
//small bug with first row now getting checked
 
public partial class UserControls_Workflow_CO2SearchResults : System.Web.UI.UserControl
{
	private string _workflowConnectionString = ConfigurationManager.ConnectionStrings["WORKFLOWConnection"].ConnectionString;
 
	private DataSet _ds;
 
	//PROPERTY NOT IMPLEMENTED YET - NOT BEING USED YET
	public DataSet CurrentDataSource
	{
		get
		{
			return _ds;
		}
 
		set
		{
			_ds = value;
		}
	}
	
	protected void Page_Load( object sender, EventArgs e )
	{
		string tempArgument = Request.Params.Get("__EVENTARGUMENT");
	
		//INITIALIZATION
		if (!Page.IsPostBack)
		{
			string[] DataKeyNames = { "ID" };
			ViewState["DataKeyNames"] = DataKeyNames;
			ViewState["SortExp"] = DataKeyNames.GetValue(0);
			ViewState["SortDir"] = SortDirection.Descending;
			ViewState["PageIndex"] = 0;
			LocalSelectAllWorkitemTypes();
			GatherCheckBoxStatus(false,false);
			this.BuildGridView(true);			
		}
				
 
		//THE "CHECK ALL" CHECKBOX IN THE HEADER WAS CLICKED
		if (tempArgument == "CHECKALL")
		{
			bool statepassedin = false;
			this.HiddenField1.Value = "false";
 
			string newpageindex = Request.Params.Get("__EVENTTARGET");
			if (newpageindex == "true")
			{
				statepassedin = true;
				this.HiddenField1.Value = "true";
			}
			
			GatherCheckBoxStatus(true,statepassedin);
			BuildGridView(false);			
		}
 
		
 
		//A PAGER BUTTON WAS CLICKED
		if (tempArgument == "PAGERBUTTON")
		{
			string newpageindex = Request.Params.Get("__EVENTTARGET");
			int adjustedPageIndex = Int32.Parse(newpageindex) - 1;
			ViewState["PageIndex"] = adjustedPageIndex;
			GatherCheckBoxStatus(false,false);
			this.BuildGridView(false);			
		}
	}
 
	//PRESERVE THE CHECKBOX STATUS ACROSS POSTBACKS (SORTING AND PAGING)
	private void GatherCheckBoxStatus(bool PerformOverride, bool CheckState)
	{
		string[] arrIDs = this.HiddenField1.Value.Split(new char[] { '|' });
 
		if (PerformOverride)
		{
			DataSet ds = (DataSet)ViewState["DataStore"];
 
			foreach (DataRow row in ds.Tables[0].Rows)
			{				
				string ID = string.Empty;
				string[] datakeynames = (string[])ViewState["DataKeyNames"];
				ID = row[datakeynames.GetValue(0).ToString()].ToString();
 
				if (CheckState)
				{
					if (Array.IndexOf(arrIDs, ID) == -1)
					{
						this.HiddenField1.Value += ID + "|";
					}
				}
				else
				{
					if (Array.IndexOf(arrIDs, ID) != -1)
					{
						this.HiddenField1.Value = this.HiddenField1.Value.Replace(ID + "|", "");
					}
				}
			}
		}
		else
		{
			foreach (GridViewRow row in this.GridViewSearchResults.Rows)
			{
				CheckBox cb = (CheckBox)row.Cells[0].Controls[0];
				string ID = string.Empty;
				ID = this.GridViewSearchResults.DataKeys[row.RowIndex].Value.ToString();
 
				if (cb.Checked)
				{
					if (Array.IndexOf(arrIDs, ID) == -1)
					{
						this.HiddenField1.Value += ID + "|";
					}
				}
				else
				{
					if (Array.IndexOf(arrIDs, ID) != -1)
					{
						this.HiddenField1.Value = this.HiddenField1.Value.Replace(ID + "|", "");
					}
				}
			}
		}
	}
 
 
	//BUILD A TEMPORARY DATASET
	//FUTURE VERSIONS SHOULD USE A PROPERTY FOR THIS
	public void LocalSelectAllWorkitemTypes()
	{
		DataSet ds = new DataSet();
 
		if (ViewState["DataStore"] == null)
		{
			using (SqlConnection connection = new SqlConnection(_workflowConnectionString))
			{
				using (SqlCommand command = new SqlCommand("SelectAllWorkitemTypesTEST", connection))
				{
					command.CommandType = CommandType.StoredProcedure;
					using (SqlDataAdapter adapter = new SqlDataAdapter(command))
					{
						adapter.Fill(ds);
					}
				}
			}
 
			bool chkBool = false;
 
			ds.Tables[0].Columns.Add("chk", chkBool.GetType());
 
			ViewState["DataStore"] = ds;			
		}		
	}
 
	//CLEAR ALL COLUMNS AND REBUILD THE GRIDVIEW PROGRAMMATICALLY
	private void BuildGridView(bool ToggleSort)
	{
		DataSet ds = (DataSet)ViewState["DataStore"];
		this.GridViewSearchResults.AutoGenerateColumns = false;
		this.GridViewSearchResults.DataKeyNames = (string[])ViewState["DataKeyNames"];
		this.GridViewSearchResults.Columns.Clear();
		this.GridViewSearchResults.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
 
		CheckBoxField cbf = new CheckBoxField();
		cbf.DataField = ds.Tables[0].Columns["chk"].ToString();
		cbf.HeaderText = "";
		cbf.HeaderStyle.ForeColor = System.Drawing.Color.White;
		cbf.HeaderStyle.BackColor = System.Drawing.Color.Black;	
 
		this.GridViewSearchResults.Columns.Add(cbf);
 
		foreach (DataColumn dc in ds.Tables[0].Columns)
		{
			if (dc.ColumnName != "chk")
			{
			
				BoundField bf = new BoundField();				
				
				
 
				bf.HeaderText = dc.ColumnName;
				bf.DataField = dc.ColumnName;
				bf.HeaderStyle.ForeColor = System.Drawing.Color.White;
				bf.HeaderStyle.BackColor = System.Drawing.Color.Black;
				bf.SortExpression = dc.ColumnName;
 
				this.GridViewSearchResults.Columns.Add(bf);
			}
		}
 
		string sortExp = (string)ViewState["SortExp"];
		SortDirection sd = (SortDirection)ViewState["SortDir"];
		string sortDir = "";
 
		if (ToggleSort)
		{
			if (sd == SortDirection.Ascending)
			{
				sortDir = " DESC";
				ViewState["SortDir"] = SortDirection.Descending;
			}
			else
			{
				sortDir = " ASC";
				ViewState["SortDir"] = SortDirection.Ascending;
			}
			ds.Tables[0].DefaultView.Sort = sortExp + sortDir;
		}
		else
		{
			if (sd == SortDirection.Ascending)
			{
				sortDir = " ASC";
			}
			else
			{
				sortDir = " DESC";
			}
			ds.Tables[0].DefaultView.Sort = sortExp + sortDir;
		}		
		
		this.GridViewSearchResults.DataSource = ds.Tables[0].DefaultView;
		this.GridViewSearchResults.PageIndex = (int)ViewState["PageIndex"];	
		ViewState["DataStore"] = ds;
		this.GridViewSearchResults.DataBind();
	}
		
 
	protected void GridViewSearchResults_RowDataBound( object sender, GridViewRowEventArgs e)
	{
		//ADD CHECKBOX TO HEADER ROW (TO SUPPORT "CHECK ALL" FUNCTIONALITY)
		if (e.Row.RowType == DataControlRowType.Header)
		{
			try
			{
				CheckBox cb = new CheckBox();
				cb.Checked = false;
 
				if (HiddenField2.Value == "true")
				{
					cb.Checked = true;
				}
 
				cb.ID = "newchecked";
				cb.Attributes.Add("onclick", "CheckAllClicked(this)");
				TableCell tc = new TableCell();
 
				tc.ID = "tc";
				tc.BackColor = System.Drawing.Color.Black;
				tc.Style.Add("border-bottom-style", "none");
				e.Row.Cells.AddAt(0, tc);
				e.Row.Cells[0].Controls.Add(cb);
				e.Row.ToolTip = "header";
			}
			catch (Exception ee)
			{
				System.Diagnostics.Debug.WriteLine(ee.ToString());
			}
		}
 
 
 
		//ADD TOOLTIP (DATA KEY NAMES) TO CHECKBOX FOR USE LATER WHILE GATHERING CHECK BOX STATE
		if (e.Row.RowType == DataControlRowType.DataRow)
		{
			string[] arrIDs = this.HiddenField1.Value.Split(new char[] { '|' });
			CheckBox cb = (CheckBox)e.Row.Cells[0].Controls[0];
			cb.Enabled = true;
			string ID = this.GridViewSearchResults.DataKeys[e.Row.RowIndex].Value.ToString();
			cb.ToolTip = this.GridViewSearchResults.DataKeyNames[0].ToString();
			if (Array.IndexOf(arrIDs, ID) != -1)
			{
				cb.Checked = true;
			}
		}
 
 
		//BUILD CUSTOM PAGER
		if (e.Row.RowType == DataControlRowType.Pager)
		{
			DataSet ds = new DataSet();
 
			ds = (DataSet)ViewState["DataStore"];
 
			if (ds.Tables[0].Rows.Count > 0)
			{
				int recordcount = ds.Tables[0].Rows.Count;
				int pagecount = recordcount / this.GridViewSearchResults.PageSize;
 
				for (int i = 0; i <= pagecount; i++)
				{
					Button pagerBtn = new Button();
					
					pagerBtn.Attributes.Add("onclick", "RespondToPagerClick(this)");
					pagerBtn.ID = "pagerBtn" + i.ToString();
 
					pagerBtn.Text = (i + 1).ToString();
 
 
					if (ViewState["PageIndex"] != null)
					{
						if (i == (int)ViewState["PageIndex"])
						{
							pagerBtn.Enabled = false;
							pagerBtn.Style.Add(HtmlTextWriterStyle.BorderColor, "Red");
						}
						else
						{
							pagerBtn.Enabled = true;
						}
					}
 
					PlaceHolder ph = (PlaceHolder)e.Row.FindControl("phPager");
 
					Label countItems = (Label)e.Row.FindControl("LabelTotalWorkItems");
 
					countItems.Text = ("(" + recordcount.ToString() + " total results)");
 
					ph.Controls.Add(pagerBtn);
				}
			}
		}
	}
		
 
	protected void GridViewSearchResults_Sorting( object sender, GridViewSortEventArgs e )
	{
		ViewState["SortExp"] = e.SortExpression;
		GatherCheckBoxStatus(false, false);
		BuildGridView(true);		
	}
}
 
 
 
 
 
 
 
 
MARKUP:
 
<%@ Control Language="C#" EnableViewState="true" AutoEventWireup="true" CodeFile="CO2SearchResults.ascx.cs" Inherits="UserControls_Workflow_CO2SearchResults" %>
 
 
 
<%--//Most stable version to date.  CHECK ALL functionality is working
//small bug with first row now getting checked--%>
 
 
<script type="text/javascript">
 
				function SortValid()
        {					
						__doPostBack(1,'SORTVALID');              
        }
        
        
        function RespondToPagerClick(current)
        {					
						__doPostBack(current.value,'PAGERBUTTON');              
        }
        
        function CheckAllClicked(current)
        {					
						__doPostBack(current.checked,'CHECKALL');              
        }
        
        
        function CheckBoxChecked(current)
        {					
						theForm.somesecret.value = current.now_checked;             												
        }    
</script>
 
<style type="text/css">
	.gridview td  
	{
		border-bottom: solid 2px black; 
		padding:10px 10px 10px 10px;
	}
</style> 
 
<asp:GridView
	CssClass="gridview" 
	ID="GridViewSearchResults" 
	runat="server" 
	AllowPaging="True" 	
	AllowSorting="true"
	GridLines="None"	
	Height="400px" 	
	OnRowDataBound="GridViewSearchResults_RowDataBound"
	EmptyDataText="No Matching Records Found" 
	AutoGenerateColumns="False" 
	Width="100%" 
	onsorting="GridViewSearchResults_Sorting" >
	
	<PagerTemplate>		
	<div style="text-align:right;">
		<table id="table1" runat="server">
			<tr>
				<td style="border-bottom-style:none;">
					<asp:Label ID="Label2" runat="server" Text="Results:  "></asp:Label>
				</td>
				<td style="border-bottom-style:none;">
					<asp:PlaceHolder ID="phPager" runat="server"></asp:PlaceHolder>
				</td>
				<td style="border-bottom-style:none;">
					<asp:Label ID="LabelTotalWorkItems" runat="server" Text="0 items found"></asp:Label>
				</td>
			</tr>
		</table>	
		</div>
	</PagerTemplate>	
</asp:GridView>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:HiddenField ID="HiddenField2" runat="server" Value="false" />

Open in new window

Member_2_2556239

I have found a solution... I was adding the control in Page_init where taht should be page_load. Thanks for your reply.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.