473,407 Members | 2,326 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

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(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
6 18538
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
9,735 Expert Mod 8TB
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
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, 887 views)
May 6 '09 #4
Frinavale
9,735 Expert Mod 8TB
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
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
9,735 Expert Mod 8TB
I don't see any code that set's the TextBox ID to "txtAttendance"...
Jun 1 '09 #7

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

Similar topics

2
by: Jacksm | last post by:
How can I align an asp:table columns with gridview columns (the widths)? I have tried setting table.column(0).width = gridview.column(0).width at page_load but it doesn't work. Thanks in advance
1
by: =?Utf-8?B?SGFycnkgS2Vjaw==?= | last post by:
I have a GridView that I dynamically add columns to in code. The way that my code is written, everything works properly if I use GridView.Columns.Add to simply add the columns to the end of the...
3
by: Fritz the Cat | last post by:
Hi I have a long column of data. I'd like that to wrap into 5 columns, like a newspaper article how to do? thanks
2
by: sivagururaja | last post by:
Hi All, How can i sorting the Gridview Columns via the code behind. When i tried to sorting the column it doesn't work. SqlConnection con = new SqlConnection("Connection string");...
0
by: Don Miller | last post by:
I'd like to use a programmatically bound GridView to display a dataset (or work with a datareader) that may include everchanging numbers of database columns, in unpredictable order, with varying...
3
by: Steve B. | last post by:
Hi, I'd like to apply a css class on all cells in all gridviews in my app. To achieve that, I have to set hte item-style cssclass property of each columns. If I add this to my skin file : ...
3
by: mudassir368 | last post by:
--This is the html code <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"> <Columns>...
2
by: =?Utf-8?B?SmF5IFBvbmR5?= | last post by:
Based on wether a row is selected in a GridView I need to HIDE the last two columns of a gridview. I do NOT need to make the cells invisible I want to hide the entire column. When I set the...
4
by: Craig Buchanan | last post by:
I dynamically add data-bound templates to a gridview in my ascx control. while this works correctly when the gridview is databound to the datatable, i'm having issues on postback. i would like...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.