Looping Through a Dynamic Table and extract cell values c# - c#

I am creating a dynamic table with X amount of rows and 2 columns. This is being stored in the view state.
How can I get the values of each cell per row?
Please see my code example:
<p>How many rows?<asp:TextBox ID="txtNoSitesDeployed" runat="server"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /></p>
<asp:Table ID="dt" runat="server">
</asp:Table>
<asp:Button ID="btnGenerateEmail" runat="server" Text="Generate Email Content Bulk" onclick="btnGenerateEmail_Click" />
<p>
<asp:Label ID="lblTemplate" runat="server" Text=""></asp:Label>
</p>
Please see code-behind:
public partial class _Default : System.Web.UI.Page
{
protected int Rows
{
get
{
return ViewState["Rows"] != null ? (int)ViewState["Rows"] : 0;
}
set
{
ViewState["Rows"] = value;
}
}
protected int Columns
{
get
{
return ViewState["Columns"] != null ? (int)ViewState["Columns"] : 0;
}
set
{
ViewState["Columns"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
this.Rows = Int32.Parse(txtNoSitesDeployed.Text);
this.Columns = 2;
}
}
protected void Button1_Click (object sender, System.EventArgs e)
{
// Total number of rows.
int rowCnt;
// Current row count.
int rowCtr;
// Total number of cells per row (columns).
int cellCtr;
// Current cell counter.
int cellCnt;
rowCnt = Rows;
for(rowCtr=1; rowCtr <= rowCnt; rowCtr++)
{
// Create a new row and add it to the table.
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
var txtSiteName = new TextBox();
txtSiteName.ID = "txtSiteName-" + rowCtr;
txtSiteName.ToolTip = "Enter site name";
cell1.Controls.Add(txtSiteName);
//add cell to row
row.Cells.Add(cell1);
TableCell cell2 = new TableCell();
var ddltBU = new DropDownList();
ddltBU.ID = "ddltBU-" + rowCtr;
ddltBU.Items.Add(new ListItem("fruit", "fruit"));
cell2.Controls.Add(ddltBU);
//add cell to row
row.Cells.Add(cell2);
//add row to dt
dt.Rows.Add(row);
}
}
protected void btnGenerateEmail_Click(object sender, EventArgs e)
{
foreach(TableRow row in dt.Rows)
{
foreach(TableCell cell in dt.Rows)
{
Response.Write(cell.Text);
}
}
}
}
I can't seem to access the cell values.
Any help would be greatly appreciated

Related

Need to sum up the checked text box values in telerik grid

i have created a telerik grid for small payment module
in this module i have selected two checkbox and enter a amount,i need the total amount to be displayed in the donation amount label
The current code is to sum up the values displayed in the second column,and saving the values in session and passsing to next page.
Gridview
<telerik:GridTemplateColumn FilterControlAltText="Filter TemplateColumn3 column" UniqueName="TemplateColumn3">
<ItemTemplate>
<asp:TextBox ID="txt_amnt" runat="server"></asp:TextBox> </td>
</ItemTemplate>
</telerik:GridTemplateColumn>
c# code
protected void chk_box_CheckedChanged(object sender, EventArgs e)
{
if (ViewState["dt"].ToString().Trim() != "NULL")
{
dt = (DataTable)ViewState["dt"];
}
if (dt.Columns.Count == 0)
{
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Amount");
}
CheckBox chk = (CheckBox)sender;
if (chk.Checked == true)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count-1 ]["Id"] = ((Label)chk.FindControl("lb_id")).Text.Trim();
dt.Rows[dt.Rows.Count - 1]["Name"] = ((Label)chk.FindControl("lb_donation")).Text.Trim();
dt.Rows[dt.Rows.Count - 1]["Amount"] = ((Label)chk.FindControl("lb_amount")).Text.Trim();
// dt.Rows[dt.Rows.Count + 1]["chkstatus"] = ((Label)chk.FindControl("lb_amount")).ToString().Trim();
}
else {
for (int i = 0; i < dt.Rows.Count; i++)
{
if(((Label)chk.FindControl("lb_id")).Text.Trim()==dt.Rows[i]["Id"].ToString().Trim())
{ dt.Rows.RemoveAt(i); }
}
}
ViewState["dt"] = dt;
double tamount = 0;
for (int i2 = 0; i2 < dt.Rows.Count; i2++)
{
tamount = tamount + Convert.ToDouble(dt.Rows[i2]["Amount"]);
}
lb_tamount.Text = tamount.ToString() ;
}
I believe your code for the CheckBox will always hit error.
How can you find a control inside a CheckBox ? Secondly your code is not complete as per the result you are showing. Anyway here is the idea how you can get checked item in your RadGrid.
First you need loop the RadGrid to get all checked CheckBox.
Then sum up the total and put it to the label.
This code just to mock up for your scenario. Please use TryParse to get the int value to ensure no converting error.
Code Behind
protected void chkCheck_CheckedChanged(object sender, EventArgs e)
{
// Variable
int total = 0;
int amt = 0;
int donateAmt = 0;
foreach (GridDataItem item in rg.Items)
{
// Find Control
CheckBox chkCheck = item.FindControl("chkCheck") as CheckBox;
Label lblAmount = item.FindControl("lblAmount") as Label;
TextBox txtAmount = item.FindControl("txtAmount") as TextBox;
// Reset Amount
amt = 0;
donateAmt = 0;
// Check
if (chkCheck != null && chkCheck.Checked)
{
// Check & Get Value
if (lblAmount != null && txtAmount != null)
{
// Check & Set
if (lblAmount.Text.Trim() != string.Empty)
amt = Convert.ToInt32(lblAmount.Text.Trim());
// Check & Set
if (txtAmount.Text != string.Empty)
donateAmt = Convert.ToInt32(txtAmount.Text.Trim());
// Check current Amount in stock and donate amt
if (donateAmt > amt)
{
donateAmt = amt;
txtAmount.Text = donateAmt + "";
}
// Reset to the text
}
total += donateAmt;
}
}
lblTotal.Text = total + "";
}

asp.net content lost in dynamically generated table

I'm trying to use an ajax panel to add keep multiple images added to table cells dynamically. Thing is when I add the second image, the first one dissapears.
Its really just a silly example to try and get ajax controls working for another project.
I'm putting an image of Bill Gates in row 3, column 3 and an image of Steve Jobs in row 1, column 5. I have a button to place each image.
I can't seem to get both to display at the same time.
I have written a function to generate the cell id (GenerateTableCellID), as I've been told I would need to to this. Also there is a function to extract the cell and row in a tuple (GetColumnAndRow).
I'm not sure how to use a Session object to save the data. I thought using AJAX would be the answer, though I think I'm missing a major aspect of it.
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div id="tablePlaceHolder" runat="server"></div>
<asp:Button ID="tblButton2" runat="server" Text="Add Steve Jobs" OnClick="tblButton_Click_Jobs" />
<asp:Button ID="tblButton" runat="server" Text="Add Bill Gates" OnClick="tblButton_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
int tableSize = 5;
var t = new HtmlTable();
t.ID = "myTable";
var placeHolderURL = "http://wiki.tripwireinteractive.com/images/4/47/Placeholder.png";
for (int r = 0; r < tableSize; r++)
{
var tableRow = new HtmlTableRow();
tableRow.ID = "row_" + r.ToString();
for (int c = 0; c < tableSize; c++)
{
var tableCell = new HtmlTableCell();
var id = GenerateTableCellID(r, c);
tableCell.ID = id;
tableCell.Height = "20";
tableCell.Width = "20";
tableCell.InnerHtml = string.Format("<img src='{0}' width='20' height='20' />", placeHolderURL);
tableRow.Controls.Add(tableCell);
}
t.Controls.Add(tableRow);
}
tablePlaceHolder.Controls.Add(t);
}
protected void tblButton_Click(object sender, EventArgs e)
{
int c =2;
int r = 2;
var id = GenerateTableCellID(c, r);
var image = GenerateImage("http://www.mnn.com/sites/default/files/billgates.jpg");
var cell = (HtmlTableCell)UpdatePanel2.FindControl(id);
cell.InnerHtml = "";
cell.Controls.Add(image);
}
protected void tblButton_Click_Jobs(object sender, EventArgs e)
{
int c = 4;
int r = 0;
var id = GenerateTableCellID(c, r);
var image = GenerateImage("http://images.boomsbeat.com/data/images/full/209/jobs-jpg.jpg");
var cell = (HtmlTableCell)UpdatePanel2.FindControl(id);
cell.InnerHtml = "";
cell.Controls.Add(image);
}
protected Image GenerateImage(string url)
{
var image = new Image();
image.ImageUrl = url;
image.Width = 20;
image.Height = 20;
return image;
}
protected string GenerateTableCellID(int c, int r)
{
return "column_" + c.ToString() + "_row_" + r.ToString();
}
protected Tuple<int, int> GetColumnAndRow(string tableCellID)
{
string[] splitString = tableCellID.Split('_');
int column, row;
if (Int32.TryParse(splitString[1], out column) && Int32.TryParse(splitString[3], out row))
{
return new Tuple<int, int>(column, row);
}
else
{
return null;
}
}
It is because at every update you clear the html present before by cell.InnerHtml = ""; remove this and try
protected void tblButton_Click_Jobs(object sender, EventArgs e)
{
int c = 4;
int r = 0;
var id = GenerateTableCellID(c, r);
var image = GenerateImage("http://images.boomsbeat.com/data/images/full/209/jobs-jpg.jpg");
var cell = (HtmlTableCell)UpdatePanel2.FindControl(id);
//cell.InnerHtml = "";
cell.Controls.Add(image);
}
As mentioned on the Page LifyCycle your table is created everytime when you do reload page (does not matter is this postback or not). Also you could read this post. In other words, it is not proper way store your data in the dynamic generated controls, because you lose your data on page load.
But if it is necessary for you could use AJAX methods ($.get and $.post, not UpdatePanel) to get data from the backend and add this to generated control on the client side

problem with binding expression for gridview

Suppose I have the below class
public partial class invoice
{
public list<lineitem> lineitem;
}
public partial class lineitem
{
private Quantity quantity = new Quantity();
public Quantity Quantity
{
get { return quantity; }
set { quantity = value; }
}
}
How do I bind the value to the gridview.
public void lbluom_OnDataBinding(object sender, System.EventArgs e)
{
for (int i = 0; i < invoicetransmit.Invoice.Count; i++)
{
Label lbl = (Label)sender;
lbl.Text =
invoicetransmit.Invoice[0].LineItem[i].Quantity.Value.ToString();
}
If I do this the values in the gridview are being overwritten with the latest values...and this one below
public void lbluom_OnDataBinding(object sender, System.EventArgs e)
{
for (int i = 0; i < invoicetransmit.Invoice.Count; i++)
{
Label lbl = (Label)sender;
lbl.Text = Eval("Value")
} property does not exist.
}
}
This is how i added values to the grid
public void Addtogrid()
{
//var lineItems = (Session["BillXML"] as InvoiceTransmission).Invoice[0].LineItem;
invoicetransmit.Invoice[0].LineItem.Add(new LineItem {MaterialCode = MaterialCode.Text, ChargeCode = ChargeCode.Text, CostCenter = CostCenter.Text, GLAccount = GLAccount.Text });
//lineItems.Add(new LineItem { MaterialCode=MaterialCode.Text,ChargeCode=ChargeCode.Text,CostCenter=CostCenter.Text,GLAccount=GLAccount.Text});
for (int i = 0; i < invoicetransmit.Invoice[0].LineItem.Count; i++)
{
invoicetransmit.Invoice[0].LineItem[i].Quantity.UOMCode = UOM.Text;
invoicetransmit.Invoice[0].LineItem[i].Quantity.Value = Convert.ToDecimal(Quantity.Text);
invoicetransmit.Invoice[0].LineItem[i].UnitPrice.Value = Convert.ToDecimal(Price.Text);
//invoicetransmit.Invoice[0].LineItem[i].TotalNetAmount = (invoicetransmit.Invoice[0].LineItem[i].Quantity.Value) * (invoicetransmit.Invoice[0].LineItem[i].UnitPrice.Value);
invoicetransmit.Invoice[0].LineItem[i].TotalNetAmount = ( Convert.ToDecimal(Quantity.Text) )* (Convert.ToDecimal(Price.Text));
GridView1.DataSource = invoicetransmit.Invoice[0].LineItem;
// GridView1.DataSource = lineItems;
GridView1.DataBind();
//}
Please help me resolve this question
Try the RowDataBound event
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = (Label) e.Row.FindControl("Label1");
if(lbl!=null)
{
lbl.Text = invoicetransmit.Invoice[0].LineItem[e.Row.RowIndex].Quantity.Value.ToString();
}
}
}

Creating a header row with buttons in a Custom GridView

After posting this: Custom Header in GridView
...I have a related problem. I have added the table row during OnDataBound, and it shows up, the links are clickable. There are two problems with adding it here: first, if a postback occurs that doesn't DataBind, the row disappears; second, no events are happening when the LinkButtons are clicked. Here is the OnDataBound code:
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
// Hook up the handler to create the Selection header/footer
// TODO: Wrap this in a function sometime
Table table = (Table)Controls[0];
GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
// TODO: should add css classes
TableHeaderCell cell = new TableHeaderCell();
cell.ColumnSpan = Columns.Count + 1; // plus 1 for the checkbox column
cell.HorizontalAlign = HorizontalAlign.Left; // do this or css?
HtmlGenericControl label = new HtmlGenericControl("label");
label.InnerText = "Select:";
selectNoneLK = new LinkButton();
selectNoneLK.ID = "SelectNoneLK";
selectNoneLK.Text = "None";
selectNoneLK.Click += SelectNoneLK_Click;
//selectNoneLK.CommandName = "SelectNone";
//selectNoneLK.Command += SelectNoneLK_Click;
selectAllLK = new LinkButton();
selectAllLK.ID = "SelectAllLK";
selectAllLK.Text = "All on this page";
//selectAllLK.CommandName = "SelectAll";
//selectAllLK.Command += SelectAllLK_Click;
selectAllLK.Click += SelectAllLK_Click;
cell.Controls.Add(label);
cell.Controls.Add(selectNoneLK);
cell.Controls.Add(selectAllLK);
row.Controls.Add(cell);
// Find out where to put this row
int rowIndex = 0;
if(SelectionMode == SelectionMode.AboveHeader)
{
rowIndex = 0;
}
else if(SelectionMode == SelectionMode.BelowHeader)
{
rowIndex = 1;
}
else if(SelectionMode == SelectionMode.AboveFooter)
{
rowIndex = table.Rows.Count;
}
else if(SelectionMode == SelectionMode.BelowFooter)
{
rowIndex = table.Rows.Count + 1;
}
table.Rows.AddAt(rowIndex, row);
}
You can try putting it in the RowCreated Event, while the header is being created. This might also fix your problem with the LinkButtons not working.
void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.Header)
{
...your code here
}

ASP.NET GridView second header row to span main header row

I have an ASP.NET GridView which has columns that look like this:
| Foo | Bar | Total1 | Total2 | Total3 |
Is it possible to create a header on two rows that looks like this?
| | Totals |
| Foo | Bar | 1 | 2 | 3 |
The data in each row will remain unchanged as this is just to pretty up the header and decrease the horizontal space that the grid takes up.
The entire GridView is sortable in case that matters. I don't intend for the added "Totals" spanning column to have any sort functionality.
Edit:
Based on one of the articles given below, I created a class which inherits from GridView and adds the second header row in.
namespace CustomControls
{
public class TwoHeadedGridView : GridView
{
protected Table InnerTable
{
get
{
if (this.HasControls())
{
return (Table)this.Controls[0];
}
return null;
}
}
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
this.CreateSecondHeader();
}
private void CreateSecondHeader()
{
GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);
TableCell left = new TableHeaderCell();
left.ColumnSpan = 3;
row.Cells.Add(left);
TableCell totals = new TableHeaderCell();
totals.ColumnSpan = this.Columns.Count - 3;
totals.Text = "Totals";
row.Cells.Add(totals);
this.InnerTable.Rows.AddAt(0, row);
}
}
}
In case you are new to ASP.NET like I am, I should also point out that you need to:
1) Register your class by adding a line like this to your web form:
<%# Register TagPrefix="foo" NameSpace="CustomControls" Assembly="__code"%>
2) Change asp:GridView in your previous markup to foo:TwoHeadedGridView. Don't forget the closing tag.
Another edit:
You can also do this without creating a custom class.
Simply add an event handler for the DataBound event of your grid like this:
protected void gvOrganisms_DataBound(object sender, EventArgs e)
{
GridView grid = sender as GridView;
if (grid != null)
{
GridViewRow row = new GridViewRow(0, -1,
DataControlRowType.Header, DataControlRowState.Normal);
TableCell left = new TableHeaderCell();
left.ColumnSpan = 3;
row.Cells.Add(left);
TableCell totals = new TableHeaderCell();
totals.ColumnSpan = grid.Columns.Count - 3;
totals.Text = "Totals";
row.Cells.Add(totals);
Table t = grid.Controls[0] as Table;
if (t != null)
{
t.Rows.AddAt(0, row);
}
}
}
The advantage of the custom control is that you can see the extra header row on the design view of your web form. The event handler method is a bit simpler, though.
I took the accepted answer approach, but added the header to the existing GridView instead of a custom inherited GridView.
After I bind my GridView, I do the following:
/*Create header row above generated header row*/
//create row
GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);
//spanned cell that will span the columns I don't want to give the additional header
TableCell left = new TableHeaderCell();
left.ColumnSpan = 6;
row.Cells.Add(left);
//spanned cell that will span the columns i want to give the additional header
TableCell totals = new TableHeaderCell();
totals.ColumnSpan = myGridView.Columns.Count - 3;
totals.Text = "Additional Header";
row.Cells.Add(totals);
//Add the new row to the gridview as the master header row
//A table is the only Control (index[0]) in a GridView
((Table)myGridView.Controls[0]).Rows.AddAt(0, row);
/*fin*/
This article should point you in the right direction. You can programmatically create the row and add it to the collection at position 0.
Note for those who choose to use RowDataBound Method in VB.NET
If you end up with too many extra header rows popping up, add an If Statement that only proceeds if the gridview's header row is nothing (meaning it is the one currently being bound)
If grid.HeaderRow Is Nothing Then
You will have to create a class which extends gridview then override the CreateRow method.
try this as a starting point
Add t.EnableViewState = false; after you add the row:
Dim t As Table = TryCast(grid.Controls(0), Table)
If t IsNot Nothing Then
t.Rows.AddAt(0, row)
End If
t.EnableViewState = false;
Please refer to https://stackoverflow.com/a/9333714/1060656
i created this solution example
To run in your local system will will need to create 2 files ( one for the control and one aspx) you can either do it one project or 2 projects.
GridViewPlus ==> Control class
GridViewPlusCustomHeaderRows ==> a collection to hold custom header class
CustomHeaderEventArgs ==> Event Args when custom header row is created
aspx file ==> Test program
public class GridViewPlus : GridView
{
public event EventHandler<CustomHeaderEventArgs> CustomHeaderTableCellCreated;
private GridViewPlusCustomHeaderRows _rows;
public GridViewPlus() : base ()
{
_rows = new GridViewPlusCustomHeaderRows();
}
/// <summary>
/// Allow Custom Headers
/// </summary>
public bool ShowCustomHeader { get; set; }
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
[MergableProperty(false)]
public GridViewPlusCustomHeaderRows CustomHeaderRows
{
get {return _rows; }
}
protected virtual void OnCustomHeaderTableCellCreated(CustomHeaderEventArgs e)
{
EventHandler<CustomHeaderEventArgs> handler = CustomHeaderTableCellCreated;
// Event will be null if there are no subscribers
if (handler != null)
{
// Use the () operator to raise the event.
handler(this, e);
}
}
protected override void OnRowCreated(GridViewRowEventArgs e)
{
if (ShowCustomHeader && e.Row.RowType == DataControlRowType.Header) return;
base.OnRowCreated(e);
}
protected override void PrepareControlHierarchy()
{
//Do not show the Gridview header if show custom header is ON
if (ShowCustomHeader) this.ShowHeader = false;
base.PrepareControlHierarchy();
//Safety Check
if (this.Controls.Count == 0)
return;
bool controlStyleCreated = this.ControlStyleCreated;
Table table = (Table)this.Controls[0];
int j = 0;
if (CustomHeaderRows ==null )return ;
foreach (TableRow tr in CustomHeaderRows)
{
OnCustomHeaderTableCellCreated(new CustomHeaderEventArgs(tr,j));
table.Rows.AddAt(j, tr);
tr.ApplyStyle(this.HeaderStyle);
j++;
}
}
}
public class GridViewPlusCustomHeaderRows : System.Collections.CollectionBase
{
public GridViewPlusCustomHeaderRows()
{
}
public void Add(TableRow aGridViewCustomRow)
{
List.Add(aGridViewCustomRow);
}
public void Remove(int index)
{
// Check to see if there is a widget at the supplied index.
if (index > Count - 1 || index < 0)
// If no widget exists, a messagebox is shown and the operation
// is cancelled.
{
throw (new Exception("Index not valid"));
}
else
{
List.RemoveAt(index);
}
}
public TableRow Item(int Index)
{
// The appropriate item is retrieved from the List object and
// explicitly cast to the Widget type, then returned to the
// caller.
return (TableRow)List[Index];
}
}
public class CustomHeaderEventArgs : EventArgs
{
public CustomHeaderEventArgs(TableRow tr ,int RowNumber )
{
tRow = tr;
_rownumber = RowNumber;
}
private TableRow tRow;
private int _rownumber = 0;
public int RowNumber { get { return _rownumber; } }
public TableRow HeaderRow
{
get { return tRow; }
set { tRow = value; }
}
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Example1();
GridViewExtension1.CustomHeaderTableCellCreated += new EventHandler<CustomHeaderEventArgs>(GridViewExtension1_CustomHeaderTableCellCreated);
}
void GridViewExtension1_CustomHeaderTableCellCreated(object sender, CustomHeaderEventArgs e)
{
TableRow tc = (TableRow)e.HeaderRow;
tc.BackColor = System.Drawing.Color.AliceBlue;
}
private void Example1()
{
System.Data.DataTable dtSample = new DataTable();
DataColumn dc1 = new DataColumn("Column1",typeof(string));
DataColumn dc2 = new DataColumn("Column2",typeof(string));
DataColumn dc3 = new DataColumn("Column3",typeof(string));
DataColumn dc4 = new DataColumn("Column4",typeof(string));
// DataColumn dc5 = new DataColumn("Column5",typeof(string));
dtSample.Columns.Add(dc1);
dtSample.Columns.Add(dc2);
dtSample.Columns.Add(dc3);
dtSample.Columns.Add(dc4);
// dtSample.Columns.Add(dc5);
dtSample.AcceptChanges();
for (int i = 0; i < 25; i++)
{
DataRow dr = dtSample.NewRow();
for (int j = 0; j < dtSample.Columns.Count; j++)
{
dr[j] = j;
}
dtSample.Rows.Add(dr);
}
dtSample.AcceptChanges();
//GridViewExtension1.ShowHeader = false;
GridViewExtension1.ShowCustomHeader = true;
/*
*=======================================================================
* |Row 1 Cell 1 | Row 1 Col 2 (Span=2) | Row 1 Col 3 |
* | | | |
*=======================================================================
* |Row 2 Cell 1 | | | |
* | | Row 2 Col 2 | Row 2 Col 3 |Row 2 Col 4 |
*=======================================================================
*
*
*
*
* */
// SO we have to make 2 header row as shown above
TableRow TR1 = new TableRow();
TableCell tcR1C1 = new TableCell();
tcR1C1.Text = "Row 1 Cell 1";
tcR1C1.ColumnSpan = 1;
TR1.Cells.Add(tcR1C1);
TableCell tcR1C2 = new TableCell();
tcR1C2.Text = "Row 1 Cell 2";
tcR1C2.ColumnSpan = 2;
TR1.Cells.Add(tcR1C2);
TableCell tcR1C3 = new TableCell();
tcR1C3.Text = "Row 1 Cell 3";
tcR1C3.ColumnSpan = 1;
TR1.Cells.Add(tcR1C3);
GridViewExtension1.CustomHeaderRows.Add(TR1);
TableRow TR2 = new TableRow();
TableCell tcR2C1 = new TableCell();
tcR2C1.Text = "Row 2 Cell 1";
tcR2C1.ColumnSpan = 1;
TR2.Cells.Add(tcR2C1);
TableCell tcR2C2 = new TableCell();
tcR2C2.Text = "Row 2 Cell 2";
tcR2C2.ColumnSpan = 1;
TR2.Cells.Add(tcR2C2);
TableCell tcR2C3 = new TableCell();
tcR2C3.Text = "Row 2 Cell 3";
tcR2C3.ColumnSpan = 1;
TR2.Cells.Add(tcR2C3);
TableCell tcR2C4 = new TableCell();
tcR2C4.Text = "Row 2 Cell 4";
tcR2C4.ColumnSpan = 1;
TR2.Cells.Add(tcR2C4);
GridViewExtension1.CustomHeaderRows.Add(TR2);
GridViewExtension1.DataSource = dtSample;
GridViewExtension1.DataBind();
}
}
I wanted to do a similar task but required clickable buttons inside the header - none of the above worked in that case as the event handlers were not wired up (due to the sequencing of the events). In the end i used the headertemplate tag in the appropriate templatefield of the grid view. The html looks a bit more bloated but the events remain intact with no additional code behind effort. For example
<asp:TemplateField >
<HeaderTemplate>
<div>
<div style="text-align: center;padding-bottom: 5px;">
text
</div>
<div>
<asp:Button ID="Button1" runat="server" Text="Apply to all" ToolTip="Apply to all - Special Bolt On" CssClass="sub_button input_btn_5" OnClick="ApplyButton1_Click" />
</div>
</div>
</HeaderTemplate>
<ItemTemplate>....

Categories

Resources