By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,563 Members | 1,241 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,563 IT Pros & Developers. It's quick & easy.

generating gridview columns dynamically

P: 28
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(textboxes) and saves the grid as excel.
Can anybody give an idea about adding columns, if possible figureout the sample code.

Thanking you all,
May 4 '09 #1
Share this Question
Share on Google+
6 Replies


P: 28
Hi boss ,
I tried like this, it worked for me.......
Expand|Select|Wrap|Line Numbers
  1.              TemplateField objTf = new TemplateField();
  2.             //objTf.HeaderTemplate = new Gridviewtemplate();
  3.             objTf.HeaderText ="column name";
  4.             objTf.ItemTemplate = new Gridviewtemplate();
  5.             GridView1.Columns.Add(objTf);
  6.             GridView1.DataSource = objDt;
  7.             GridView1.DataBind();
  8.             GridView1.Visible = true;

now write the class as......
Expand|Select|Wrap|Line Numbers
  1. public class Gridviewtemplate : ITemplate
  2. {
  3.     public Gridviewtemplate()
  4.     {
  5.  
  6.     }
  7.  
  8.     void ITemplate.InstantiateIn(Control container)
  9.     {
  10.         TextBox objTb = new TextBox();          //Allocates the newtext box object.
  11.         objTb.Columns = 4;                            //Creates a column with size 4.
  12.         container.Controls.Add(objTb);
  13.     }
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
May 5 '09 #2

Frinavale
Expert Mod 5K+
P: 9,731
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:
Expand|Select|Wrap|Line Numbers
  1. private void InitailizeGrid()
  2. {
  3.  
  4.    //Making sure that the GridView isn't automatically generating columns that
  5.    //haven't specifically been added
  6.    GridView1.AutoGenerateColumns = false;
  7.  
  8.    for(int i=0; i<myDataSourceTable.Columns.Count -1; i++)
  9.    {
  10.       TemplateField tf = new TemplateField();
  11.       tf.HeaderText = myDataSourceTable.Columns[i].ColumnName();
  12.       Gridviewtemplate item = new Gridviewtemplate();
  13.  
  14.       GridView1.Columns.Add(tf);       
  15.    }
  16. }
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:

Expand|Select|Wrap|Line Numbers
  1. private DataTable CreateEmptyDataSource()
  2. {
  3.    DataTable theDataSource = new DataTable();
  4.    DataRow dr;
  5.    int i;  
  6.  
  7.    //Adding 6 columns to the data source
  8.    for(i=0; i<6; i++)
  9.    {
  10.       theDataSource.Columns.Add(new DataColumn("Column " + i.ToString()));
  11.    }
  12.  
  13.    //Adding 10 empty rows to the data source
  14.    for(i=0; i<10; i++)
  15.    {
  16.       dr = theDataSource.NewRow;
  17.       theDataSource.Rows.Add(dr);
  18.    }
  19. }
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 Gridviewtemplate...which ever you need to change.
May 5 '09 #3

P: 28
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.

Expand|Select|Wrap|Line Numbers
  1. for (int i = 1; i <= cols; i++)
  2.         {
  3.             HtmlTableRow objRow = new HtmlTableRow();
  4.             HtmlTableCell objCell = new HtmlTableCell();
  5.             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>";
  6.             objRow.Cells.Add(objCell);
  7.             objTbl.Rows.Add(objRow);
  8.         }
  9.         this.Controls.Add(objTbl);
  10.     }


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

Expand|Select|Wrap|Line Numbers
  1.          int col;
  2.         col = Convert.ToInt16(txtNumberOfColumns.Value);
  3.         for (int i = 1; i <= col; i++)
  4.         {
  5.             TemplateField objTf = new TemplateField();
  6.             //objTf.HeaderTemplate = new Gridviewtemplate();
  7.             TextBox objTbColname;
  8.             TextBox objTbcolwidth;
  9.             objTbColname  =  Request["txtColumnName'"+i+"'"];//not getting 
  10.                                                                                            object of textbox
  11.             objTbcolwidth = Request["txtColumnWidth'" + i + "'"];//not getting 
  12.                                                                                            object of textbox
  13.             objTf.HeaderText = objTbColname.Text;
  14.             objTf.ItemTemplate = new Gridviewtemplate(objTbcolwidth.Text);
  15.             GridView1.Columns.Add(objTf);
  16.         }
  17.         GridView1.DataSource = objDt;
  18.         GridView1.DataBind();
  19.         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 Images
File Type: jpg page.jpg (14.2 KB, 813 views)
May 6 '09 #4

Frinavale
Expert Mod 5K+
P: 9,731
You have AutoGenerateColumns = 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:


Expand|Select|Wrap|Line Numbers
  1. ///  <summary>
  2. ///  Initializes the dynamic controls within the Grid so that any events 
  3. ///  that originate from these controls, and any values within these controls
  4. ///  can be accessed and handled in the rest of the page
  5. /// </summary>
  6. /// <param name="sender">The object that raised the event.</param>
  7. /// <param name="e">The EventArgs for the event</param>
  8. private void Page_Init(Object sender , System.EventArgs e )
  9. {
  10.     Integer numColumns;
  11.  
  12.     // Trying to retrieve the number of columns that the 
  13.     // Grid had last time in order
  14.     // to recreate the Grid as it was before it was sent to the browser
  15.     // so that the dynamic controls within the Grid can be loaded correctly.
  16.     if(Integer.TryParse(Request.Params["numberOfColumns"], numColumns))
  17.     {
  18.         InitializeGrid(numColumns);
  19.     }
  20. }
  21.  
  22. private void InitializeGrid(Integer numberOfColumns)
  23. {
  24.     // Dynamically creating the Template Columns for the Grid
  25.     int i;
  26.     for(i=0; i<numberOfColumns; i++)
  27.     {
  28.             TemplateField objTf = new TemplateField();
  29.             objTf.ItemTemplate = new Gridviewtemplate("2");
  30.             GridView1.Columns.Add(objTf);
  31.     }
  32. }
  33.  
  34. private void Page_PreRender(Object sender, System.EventArgs e)
  35. {
  36.     // Saving the number of columns in the grid so that we can
  37.     // initialize it again next time
  38.     numberOfColumns.value = numberOfColumns.ToString();
  39. //  Please note that numberOfColumns is a HiddenField.
  40. }
  41.  
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.
May 6 '09 #5

P: 1
hi

i have used this code for dynamically generating column containing textboxes.
Expand|Select|Wrap|Line Numbers
  1.           TemplateField objTf = new TemplateField();
  2.             //objTf.HeaderTemplate = new Gridviewtemplate();
  3.             objTf.HeaderText ="column name";
  4.             objTf.ItemTemplate = new Gridviewtemplate();
  5.             GridView1.Columns.Add(objTf);
  6.             GridView1.DataSource = objDt;
  7.             GridView1.DataBind();
  8.             GridView1.Visible = true;
  9.  
  10.  
  11.           public class Gridviewtemplate : ITemplate
  12.          {
  13.              public Gridviewtemplate()
  14.             {
  15.  
  16.             }
  17.  
  18.            void ITemplate.InstantiateIn(Control container)
  19.           {
  20.              TextBox objTb = new TextBox();      //Allocates the newtext box object.
  21.             objTb.Columns = 4;                            //Creates a column with size 4.
  22.             container.Controls.Add(objTb);
  23.          }

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:
Expand|Select|Wrap|Line Numbers
  1.      foreach (GridViewRow gvr in this.grVwAttendance.Rows)
  2.      {
  3.         string attendance = (gvr.FindControl("txtAttendance") as TextBox).Text;
  4.      }

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


plzzz give me solution for this, very urgent!!!!!
Jun 1 '09 #6

Frinavale
Expert Mod 5K+
P: 9,731
I don't see any code that set's the TextBox ID to "txtAttendance"...
Jun 1 '09 #7

Post your reply

Sign in to post your reply or Sign up for a free account.