C# .NET - Adding Dynamically Rows and Column from database in Item template with TextBox of gridview

Asked By Kanak Kumar on 27-Sep-12 01:01 AM
Hi Everyone

I have writen a code in which i am adding columns and rows in gridview from database dynamically by click on a button that depends on drop down value. But the problem s that after view of gridview when i have entered the data in item template textbox and click on another button then gridview losses rows and columns.

Database Table
1. stonecolumn(stone,column)
2. stonerows(stone.row)

Default.aspx

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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
   
    <div>
        
        <asp:DropDownList ID="DropDownList1" runat="server" 
            DataSourceID="SqlDataSource1" DataTextField="Stone_Name" 
            DataValueField="Stone_ID">
        </asp:DropDownList>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:soniConnectionString %>" 
            SelectCommand="SELECT [Stone_Name], [Stone_ID] FROM [tblStoneMaster]">
        </asp:SqlDataSource>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
            Text="Display" />
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
            Text="GetData" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        </asp:GridView>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><asp:Label ID="Label2"
            runat="server" Text="Label"></asp:Label><asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
  
    </div>
    </form>
</body>
</html>


Default.aspx.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


namespace gridviewdemo
{
    public partial class _Default : System.Web.UI.Page
    {
        DataTable dtc = new DataTable();
        DataTable dtr = new DataTable();
        static int column, rows;
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["soniConnectionString"].ToString());
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }
        private void loadDynamicGridWithTemplateColumn()
        {
                                                                                                        #region Code for preparing the DataTable
            column = dtc.Rows.Count;
            rows = dtr.Rows.Count;
            DataTable dt = new DataTable();
            DataColumn dcol;
            if (rows == 0)
            {
                //Create an instance of DataTable
                for (int i = 0; i < column; i++)
                {
                    //Create an ID column for adding to the Datatable
                    dcol = new DataColumn(dtc.Rows[i][0].ToString(), typeof(System.String));
                    dt.Columns.Add(dcol);
                }
               
                DataRow drow = dt.NewRow();
               
                dt.Rows.Add(drow);
                                                                                                        #endregion


                //Iterate through the columns of the datatable to set the data bound field dynamically.
                
            }
            else
            {
                dcol = new DataColumn(DropDownList1.SelectedItem.Text, typeof(System.String));
                dt.Columns.Add(dcol);
                for (int i = 0; i < column; i++)
                {
                    //Create an ID column for adding to the Datatable
                    dcol = new DataColumn(dtc.Rows[i][0].ToString(), typeof(System.String));
                    dt.Columns.Add(dcol);
                }
                
                for (int j = 0; j < rows; j++)
                {
                    DataRow drow = dt.NewRow();
                    drow[DropDownList1.SelectedItem.Text] = dtr.Rows[j][0].ToString();
                    dt.Rows.Add(drow);
                }
                
            }
            foreach (DataColumn col in dt.Columns)
            {
                //Declare the bound field and allocate memory for the bound field.
                TemplateField bfield = new TemplateField();


                //Initalize the DataField value.
                bfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);


                //Initialize the HeaderText field value.
                bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);


                //Add the newly created bound field to the GridView.
                GridView1.Columns.Add(bfield);
            }
            ViewState["CurrentTable"] = dt;
            ////Initialize the DataSource
            GridView1.DataSource = dt;


            ////Bind the datatable with the GridView.
            GridView1.DataBind();
        }


        protected void Button1_Click(object sender, EventArgs e)
        {
            getcolumnsDetails();
            getrowDetails();
            loadDynamicGridWithTemplateColumn();
            Label1.Text = "Rows: " + GridView1.Rows.Count;
            Label2.Text = "Cols: " + GridView1.Columns.Count;
           
        }
        protected void getrowDetails()
        {
            if (con.State == ConnectionState.Closed)
                con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "select rows from stonerows where stone='" + DropDownList1.SelectedItem.Text + "'";
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            da.Fill(dtr);
            con.Close();
        }
        protected void getcolumnsDetails()
        {
            if (con.State == ConnectionState.Closed)
                con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "select columns from stonecolumn where stone='"+DropDownList1.SelectedItem.Text+"'";
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            da.Fill(dtc);
            con.Close();
        }


        protected void Button2_Click(object sender, EventArgs e)
        {
           
                Label3.Text = ((TextBox)GridView1.Rows[0].Cells[1].FindControl("tb1")).Text;
               
           
        }
           
                    
    }
}


GridViewTemplate.cs

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


namespace gridviewdemo
{
    public class GridViewTemplate : ITemplate
    {
        //A variable to hold the type of ListItemType.
        ListItemType _templateType;


        //A variable to hold the column name.
        string _columnName;


        //Constructor where we define the template type and column name.
        public GridViewTemplate(ListItemType type, string colname)
        {
            //Stores the template type.
            _templateType = type;


            //Stores the column name.
            _columnName = colname;
        }


        void ITemplate.InstantiateIn(System.Web.UI.Control container)
        {
            switch (_templateType)
            {
                case ListItemType.Header:
                    //Creates a new label control and add it to the container.
                    Label lbl = new Label();            //Allocates the new label object.
                    lbl.Text = _columnName;             //Assigns the name of the column in the lable.
                    container.Controls.Add(lbl);        //Adds the newly created label control to the container.
                    break;


                case ListItemType.Item:
                    //Creates a new text box control and add it to the container.
                    TextBox tb1 = new TextBox();                            //Allocates the new text box object.
                    tb1.DataBinding += new EventHandler(tb1_DataBinding);   //Attaches the data binding event.
                    tb1.Columns = 4;                                        //Creates a column with size 4.
                    container.Controls.Add(tb1);                            //Adds the newly created textbox to the container.
                    break;


                case ListItemType.EditItem:
                    //As, I am not using any EditItem, I didnot added any code here.
                    break;


                case ListItemType.Footer:
                    CheckBox chkColumn = new CheckBox();
                    chkColumn.ID = "Chk" + _columnName;
                    container.Controls.Add(chkColumn);
                    break;
            }
        }


        /// <summary>
        /// This is the event, which will be raised when the binding happens.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void tb1_DataBinding(object sender, EventArgs e)
        {
            TextBox txtdata = (TextBox)sender;
            GridViewRow container = (GridViewRow)txtdata.NamingContainer;
            object dataValue = DataBinder.Eval(container.DataItem, _columnName);
            if (dataValue != DBNull.Value)
            {
                txtdata.Text = dataValue.ToString();
            }
        }
    }
}
Jitendra Faye replied to Kanak Kumar on 01-Oct-12 02:04 AM
In another button are loading GridView again . if yes then your GridView will lost created Itemtemplate.