Monday, June 30, 2008

inserting texbox inside of the gridview

This took me awhile.. Here is my solution.

Here is an idea...
1. Create gridview
2. Create blank templatefield
3. Bind gridview
4. Grab hold of the holder like page, from, placeholder that has the gridview
5. Find "GridView" control(s).
6. Grab hold of rows
7. Insert by row.cells[i].controls.add(your control);

For some reason i couldn't add itemtemplate or edittemplate like how I could add boundfield inside of the gridview.
instead, I created an empty TemplateField

GridView myGrid = new GridView();
// add other GridView Properties and events...

TemplateField tf1 = new TemplateField();
tf1.HeaderText = "Header Text";
tf1.HeaderStyle.Width = Unit.Pixel(ScoreColunmWidth);
tf1.ItemStyle.HorizontalAlign = HorizontalAlign.Center;

myGrid.Columns.Add(tf1);


Then you need to databind the gridview. then you have a working GridView.

The code below is O = n^2... there might be better algorithms to do this. Maybe add textbox during mygrid creation. that way, there is no loop... but this is decent. Eefficiency gain by 0=1 versus n^2 is very small in this case.
Corn Chowders!

private void addTextBoxforScoreColumn()
{
var Controls = PlaceHolder1.Controls;

int rowCount = 0;

// this is O = n^2
foreach (var x in Controls)
{
if (x.ToString().Contains("GridView"))
{
GridView gridview = (GridView)x;

foreach (GridViewRow row in gridview.Rows)
{
TextBox textbox = new TextBox();
textbox.Width = 50;
textbox.ID = "x";
row.Cells[0].Controls.Add(textbox);
}
}
}
}

No comments: