generating gridview columns dynamically

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vinod allapu
    New Member
    • Apr 2009
    • 28

    generating gridview columns dynamically

    Hi boss,


    I have a gridview, bound to a datasource . Here i want to add columns dynamically containing empty textboxes. Number of columns are variant .
    The added columns are not bound to datasource they are added just for dislay.
    The user fills the data in columns(textbox es) and saves the grid as excel.
    Can anybody give an idea about adding columns, if possible figureout the sample code.

    Thanking you all,
  • vinod allapu
    New Member
    • Apr 2009
    • 28

    #2
    Hi boss ,
    I tried like this, it worked for me.......
    Code:
                 TemplateField objTf = new TemplateField();
                //objTf.HeaderTemplate = new Gridviewtemplate();
                objTf.HeaderText ="column name";
                objTf.ItemTemplate = new Gridviewtemplate();
                GridView1.Columns.Add(objTf);
                GridView1.DataSource = objDt;
                GridView1.DataBind();
                GridView1.Visible = true;

    now write the class as......
    Code:
    public class Gridviewtemplate : ITemplate
    {
        public Gridviewtemplate()
        {
            
        }
        
        void ITemplate.InstantiateIn(Control container)
        {
            TextBox objTb = new TextBox();          //Allocates the newtext box object.
            objTb.Columns = 4;                            //Creates a column with size 4.
            container.Controls.Add(objTb);
        }
    but it is adding columns at the begining of the grid. I want textbox columns to add at the end...
    can anybody help me...

    thanks to all
    Last edited by Frinavale; May 5 '09, 02:17 PM. Reason: Added code tags. Please post code in [code] [/code] tags.

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      I don't understand your problem.

      What you should be doing (that I'm not seeing in your code) dynamically creating the columns for your GridView....

      In your posted code I see you creating 1 column.

      You should have something like:
      Code:
      private void InitailizeGrid()
      {
      
         //Making sure that the GridView isn't automatically generating columns that
         //haven't specifically been added
         GridView1.AutoGenerateColumns = false;
      
         for(int i=0; i<myDataSourceTable.Columns.Count -1; i++)
         {
            TemplateField tf = new TemplateField();
            tf.HeaderText = myDataSourceTable.Columns[i].ColumnName();
            Gridviewtemplate item = new Gridviewtemplate();
      
            GridView1.Columns.Add(tf);       
         }
      }
      Your data source should contain all of the necessary columns that are required. If you want empty rows, then your data source should have empty rows in it.

      For example, if you create a table that has 6 columns and you want to display 10 empty rows then you would have to create a table that has 6 columns and 10 empty rows:

      Code:
      private DataTable CreateEmptyDataSource()
      {
         DataTable theDataSource = new DataTable();
         DataRow dr;
         int i;  
      
         //Adding 6 columns to the data source
         for(i=0; i<6; i++)
         {
            theDataSource.Columns.Add(new DataColumn("Column " + i.ToString()));
         }
      
         //Adding 10 empty rows to the data source
         for(i=0; i<10; i++)
         {
            dr = theDataSource.NewRow;
            theDataSource.Rows.Add(dr);
         }
      }
      So now the GridView will display 6 columns and 10 rows of empty text boxes.

      If this isn't what you desire....then change your data source to better reflect what you're trying to do....or change your Gridviewtemplat e...which ever you need to change.

      Comment

      • vinod allapu
        New Member
        • Apr 2009
        • 28

        #4
        Hi boss ,

        Many thanks for your answer......For better understanding of my actual requirement please see the image.

        The datatable is bound to grid according to user selected columns, if the user wants to add some more columns to grid (not to datatable) then he enters "number of columns" to add to grid then btnOk_click.

        Code:
        for (int i = 1; i <= cols; i++)
                {
                    HtmlTableRow objRow = new HtmlTableRow();
                    HtmlTableCell objCell = new HtmlTableCell();
                    objCell.InnerHtml = "<td>ColumnName</td>" + "<td><input id=\"txtColumnName" + i + "\" name=\"txtColumnName" + i + "\" runat=\"server\" type=\"text\" /></td>" + "<td>ColumnWidth</td>" + "<td><input id=\"txtColumnWidth" + i + "\" name=\"txtColumnWidth" + i + "\" runat=\"server\" type=\"text\" /></td>";
                    objRow.Cells.Add(objCell);
                    objTbl.Rows.Add(objRow);
                }
                this.Controls.Add(objTbl);
            }


        Now i am generating desired number of text boxes dynamically to give the column names of grid and textbox size in the grid columns.

        Code:
                 int col;
                col = Convert.ToInt16(txtNumberOfColumns.Value);
                for (int i = 1; i <= col; i++)
                {
                    TemplateField objTf = new TemplateField();
                    //objTf.HeaderTemplate = new Gridviewtemplate();
                    TextBox objTbColname;
                    TextBox objTbcolwidth;
                    objTbColname  =  Request["txtColumnName'"+i+"'"];//not getting 
                                                                                                   object of textbox
                    objTbcolwidth = Request["txtColumnWidth'" + i + "'"];//not getting 
                                                                                                   object of textbox
                    objTf.HeaderText = objTbColname.Text;
                    objTf.ItemTemplate = new Gridviewtemplate(objTbcolwidth.Text);
                    GridView1.Columns.Add(objTf);
                }
                GridView1.DataSource = objDt;
                GridView1.DataBind();
                GridView1.Visible = true;
        so that the user enters data into new columns and save it as excel.

        here i have two problems
        1. I am not able to get the object of dynamically generated textboxes.
        2. The newly added columns are not adding at the end of grid , insted adding
        at begining.

        please see the image..
        Attached Files
        Last edited by Frinavale; May 6 '09, 01:14 PM. Reason: Added code tags. Please post code in [code] [/code] tags.

        Comment

        • Frinavale
          Recognized Expert Expert
          • Oct 2006
          • 9749

          #5
          You have AutoGenerateCol umns = True don't you?
          Could you please post the ASP code (in the Code view of your aspx page)?

          I don't know why you're using Request to retrieve your text box values.
          I don't know why you're creating ASP code either......... ....

          The template dynamically generates the TextBoxes for you, and also dynamically creates a Header for you.

          You should not be doing anything like you are on line 5 in your first section of code that you posted. That's defeating the purposes of your template. I'm not even sure how this is really working.

          Here's the thing.

          When you dynamically create controls in your C# code and add them to your page, you have to pretty much always do this in your Page Init event.

          Why?
          Because of the ASP.NET life cycle.

          ASP.NET creates the C# Objects just before the Page Init event.
          After the Page Init event it fills these objects with the data that the user has entered. It also creates any Events that these Objects have fired depending on what the user has done.

          This means that if your controls are not dynamically created during the Page Init event, that they will not contain any text that the user has entered....they will not fire any event that either.


          So, what I recommend is that you dynamically create your Grid during the Page Init event.

          I recommend storing the number of columns that the user wants to display in a Hidden Field so that you can retrieve this number in the Page Init event:


          Code:
          ///  <summary>
          ///  Initializes the dynamic controls within the Grid so that any events 
          ///  that originate from these controls, and any values within these controls
          ///  can be accessed and handled in the rest of the page
          /// </summary>
          /// <param name="sender">The object that raised the event.</param>
          /// <param name="e">The EventArgs for the event</param>
          private void Page_Init(Object sender , System.EventArgs e )
          {
              Integer numColumns;
          
              // Trying to retrieve the number of columns that the 
              // Grid had last time in order
              // to recreate the Grid as it was before it was sent to the browser
              // so that the dynamic controls within the Grid can be loaded correctly.
              if(Integer.TryParse(Request.Params["numberOfColumns"], numColumns))
              {
                  InitializeGrid(numColumns);
              }
          }
          
          private void InitializeGrid(Integer numberOfColumns)
          {
              // Dynamically creating the Template Columns for the Grid
              int i;
              for(i=0; i<numberOfColumns; i++)
              {
                      TemplateField objTf = new TemplateField();
                      objTf.ItemTemplate = new Gridviewtemplate("2");
                      GridView1.Columns.Add(objTf);
              }
          }
          
          private void Page_PreRender(Object sender, System.EventArgs e)
          {
              // Saving the number of columns in the grid so that we can
              // initialize it again next time
              numberOfColumns.value = numberOfColumns.ToString();
          //  Please note that numberOfColumns is a HiddenField.
          }
          After this step ASP.NET will fill all of the TextBoxes dynamically generated by your template with the Text entered by the user.


          The number of rows in the Grid is going to depend on the DataSource that the grid is bound to.

          Comment

          • suma1512
            New Member
            • Jun 2009
            • 1

            #6
            generating gridview columns dynamically

            hi

            i have used this code for dynamically generating column containing textboxes.
            Code:
                      TemplateField objTf = new TemplateField();
                        //objTf.HeaderTemplate = new Gridviewtemplate();
                        objTf.HeaderText ="column name";
                        objTf.ItemTemplate = new Gridviewtemplate();
                        GridView1.Columns.Add(objTf);
                        GridView1.DataSource = objDt;
                        GridView1.DataBind();
                        GridView1.Visible = true;
            
            
                      public class Gridviewtemplate : ITemplate
                     {
                         public Gridviewtemplate()
                        {
             
                        }
             
                       void ITemplate.InstantiateIn(Control container)
                      {
                         TextBox objTb = new TextBox();      //Allocates the newtext box object.
                        objTb.Columns = 4;                            //Creates a column with size 4.
                        container.Controls.Add(objTb);
                     }

            it worked fine. but when i cant access the value entered in those textbox. i need those value to be sored in the database. i used find control but it did not work

            i gave somethin like this:
            Code:
                 foreach (GridViewRow gvr in this.grVwAttendance.Rows)
                 {
                    string attendance = (gvr.FindControl("txtAttendance") as TextBox).Text;
                 }

            but is giving error saying
            Object reference not set to an instance of an object.


            plzzz give me solution for this, very urgent!!!!!
            Last edited by Frinavale; Jun 1 '09, 01:05 PM. Reason: Added code tags. Please post code in [code] [/code] tags.

            Comment

            • Frinavale
              Recognized Expert Expert
              • Oct 2006
              • 9749

              #7
              I don't see any code that set's the TextBox ID to "txtAttendance" ...

              Comment

              Working...