Merging of Header in Gridview - c#

I encountered a problem in Gridview, I cannot merge the headers if the Gridview has no record, but if the Gridview contain a record, the headers are merging.
Here is my codes that I used to merge the headers in the Gridview
protected void grdWorkExperience_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView oGridView = (GridView)sender;
GridViewRow oGridViewRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell oTableCell = new TableCell();
oTableCell.Text = string.Empty;
oTableCell.ColumnSpan = 2;
oTableCell.BorderColor = System.Drawing.Color.White;
oGridViewRow.Cells.Add(oTableCell);
oTableCell = new TableCell();
oTableCell.Text = "Inclusive Dates(mm/dd/yyyy)";
oTableCell.ColumnSpan = 2;
oTableCell.Font.Bold = true;
oTableCell.Font.Size = 9;
oTableCell.Font.Name = "Verdana";
oTableCell.HorizontalAlign = HorizontalAlign.Center;
oTableCell.BackColor = System.Drawing.Color.FromArgb(0x33, 0x66, 0xCC);
oTableCell.ForeColor = System.Drawing.Color.White;
oTableCell.BorderColor = System.Drawing.Color.Gray;
oGridViewRow.Cells.Add(oTableCell);
oTableCell = new TableCell();
oTableCell.BorderColor = System.Drawing.Color.White;
oTableCell.ColumnSpan = 13;
oGridViewRow.Cells.Add(oTableCell);
oGridView.Controls[0].Controls.AddAt(0, oGridViewRow);
}
}
I placed that function in onRowCreated event of Gridview
What should I do to merge the Headers even if the Gridview has no record?

Move the code from OnRowCreated event to Load event of the Window/Control/Page

Related

Add hyperlink to gridview programmatically

I have a gridview and need to add controls to header row. I am able to add text, but how can I add a hyperlink to the header row.
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView HeaderGrid = (GridView)sender;
GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell HeaderCell = new TableCell();
HeaderCell.Text = "Logistics Details";
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);
GridView1.Controls[0].Controls.AddAt(0, HeaderGridRow);
HyperLink hl = new HyperLink();
hl.ID = "hlDetail";
hl.Text = "Details";
//the below line doesn't add controls
HeaderGridRow.Controls.Add(hl);
}
}
I think you would have to add the control to a specific Cell within the row, e.g.
HeaderGridRow.Cells[0].Controls.Add(hl);
Since it's a grid, it's not logical for items to exist within a row outside a cell - then there is no way to know where exactly to display it.
You probably also need to set the NavigateUrl property of the Hyperlink, otherwise it does not know where to navigate e.g.
hl.NavigateURL = "https://www.google.com"

Dynamically created and displayed jagged array of Textboxes loses its state after event handler is called.

I am trying to create a form for courses provided by a University. Based on the no of subjects obtained through a query string, a form gets generated. If the subject has electives, the user has to check a checkbox, which further generates a no of textboxes for subject names. But whenever I check the checkbox of say 2nd subject the textboxes previously displayed for 1st subject disappear.
ASP CODE
<html>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Demo : System.Web.UI.Page
{
#region variables
Label[] lb_subject_names;
TextBox[] tb_subject_names;
Label[] lb_elective;
Table[] table_electives;
CheckBox[] cb_elective;
TextBox[] tb_no_of_elective;
Button[] bt_electives_ok;
TextBox[][] tb_name_of_electives;
TextBox[][] tb_code_of_electives;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
int no_subjects = 3;// int.Parse(Request.QueryString["NoSubjects"]);
//declare
lb_subject_names = new Label[no_subjects];
tb_subject_names = new TextBox[no_subjects];
lb_elective = new Label[no_subjects];
table_electives = new Table[no_subjects];
cb_elective = new CheckBox[no_subjects];
tb_no_of_elective = new TextBox[no_subjects];
bt_electives_ok = new Button[no_subjects];
tb_name_of_electives = new TextBox[no_subjects][];
tb_code_of_electives = new TextBox[no_subjects][];
//initialize
for (int i = 0; i < no_subjects; i++)
{
lb_subject_names[i] = new Label();
tb_subject_names[i] = new TextBox();
lb_elective[i] = new Label();
table_electives[i] = new Table();
table_electives[i].BorderStyle = BorderStyle.Solid;
tb_no_of_elective[i] = new TextBox();
cb_elective[i] = new CheckBox();
cb_elective[i].AutoPostBack = true;
cb_elective[i].ID = (i).ToString();
cb_elective[i].CheckedChanged += new EventHandler(cb_elective_CheckedChanged);
bt_electives_ok[i] = new Button();
bt_electives_ok[i].Text = "OK";
bt_electives_ok[i].ID = "bt_" + (i).ToString();
bt_electives_ok[i].Click += new EventHandler(bt_electives_ok_clicked);
}
//display in form1
for (int i = 0; i < no_subjects; i++)
{
lb_subject_names[i].Text = "<br/>Subject Name : ";
form1.Controls.Add(lb_subject_names[i]);
form1.Controls.Add(tb_subject_names[i]);
lb_elective[i].Text = "Does the Subject provide Electives ?";
form1.Controls.Add(lb_elective[i]);
form1.Controls.Add(cb_elective[i]);
tb_no_of_elective[i].Visible = false;
bt_electives_ok[i].Visible = false;
form1.Controls.Add(tb_no_of_elective[i]);
form1.Controls.Add(bt_electives_ok[i]);
form1.Controls.Add(table_electives[i]);
}
}
protected void cb_elective_CheckedChanged(object sender, EventArgs e)
{
CheckBox currentCheckbox = sender as CheckBox;
int id = int.Parse(currentCheckbox.ID);
if (currentCheckbox != null && currentCheckbox.Checked)
{
tb_no_of_elective[id].Visible = true;
bt_electives_ok[id].Visible = true;
table_electives[id].Visible = true;
}
else
{
tb_no_of_elective[id].Visible = false;
bt_electives_ok[id].Visible = false;
table_electives[id].Visible = false;
}
}
protected void bt_electives_ok_clicked(object sender, EventArgs e)
{
Button button = sender as Button;
String str_id = button.ID;
int id = int.Parse(str_id.Substring(3, str_id.Length - 3));
int no_of_electives = int.Parse(tb_no_of_elective[id].Text);
tb_name_of_electives[id] = new TextBox[no_of_electives];
tb_code_of_electives[id] = new TextBox[no_of_electives];
for (int i = 0; i < no_of_electives; i++)
{
tb_name_of_electives[id][i] = new TextBox();
tb_code_of_electives[id][i] = new TextBox();
}
//row1 header
TableRow e_row1 = new TableRow();
TableCell e_cell1_1 = new TableCell();
e_cell1_1.Text = "Sr. No.";
e_row1.Controls.Add(e_cell1_1);
TableCell e_cell1_2 = new TableCell();
e_cell1_2.Text = "Subject Code";
e_row1.Controls.Add(e_cell1_2);
TableCell e_cell1_3 = new TableCell();
e_cell1_3.Text = "Subject Name";
e_row1.Controls.Add(e_cell1_3);
table_electives[id].Controls.Add(e_row1);
for (int i = 0; i < no_of_electives; i++)
{
//row2
TableRow e_row2 = new TableRow();
TableCell e_cell2_1 = new TableCell();
e_cell2_1.Text = (i + 1).ToString();
e_row2.Controls.Add(e_cell2_1);
TableCell e_cell2_2 = new TableCell();
e_cell2_2.Controls.Add(tb_code_of_electives[id][i]);
e_row2.Controls.Add(e_cell2_2);
TableCell e_cell2_3 = new TableCell();
e_cell2_3.Controls.Add(tb_name_of_electives[id][i]);
e_row2.Controls.Add(e_cell2_3);
table_electives[id].Controls.Add(e_row2);
}
}
}

Not able to store information while postback after creating dynamic dropdown in ASP.NET

here is my code
after button 2 click event it is creating the dropdown in table rows but when I try to save by button 1 click event it just disappear. I have not find any solution regarding this. I have used find control view State etc but it's not helping.
I want to store selected values of dropdown after button_1 click event starts.
public partial class StudentClassSectionMapping : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ClassCode.Enabled = false;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
UpdateModalShowFlag.Value = "true";
Check.Value = "true";
CreateTableRows();
}
private void CreateTableRows()
{
long h = long.Parse(LinkButtonIdCarrier.Value);
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allStudentsInClass = StudentsClassSectionMapping.GetStudentsinClass(h);
ClassMaster.ClassMasterForm classCode = Schoolclasses.GetInfo(h);
ClassCode.Text = classCode.cCode;
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allSectionsInClass = StudentsClassSectionMapping.GetSectionsinClass(h);
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm studentList in allStudentsInClass)
{
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
TableCell cell3 = new TableCell();
DropDownList t = new DropDownList();
t.Items.Add("No Section");
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm sectionList in allSectionsInClass)
{
t.Items.Add(sectionList.ssSection);
t.Items[t.Items.Count - 1].Value = sectionList.ssSectionID.ToString();
}
t.Attributes.Add("class", "form-control");
t.ID = studentList.ssStudentId.ToString();
cell1.Text = studentList.ssName;
cell2.Text = studentList.ssRegistrationNumber;
cell3.Controls.Add(t);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
row.Cells.Add(cell3);
Table1.Rows.Add(row);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTableRows();
long h = long.Parse(LinkButtonIdCarrier.Value);
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allStudentsInClass = StudentsClassSectionMapping.GetStudentsinClass(h);
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm studentList in allStudentsInClass)
{
DropDownList d = Table1.FindControl(studentList.ssStudentId.ToString()) as DropDownList;
if (d != null)
{
if (d.SelectedIndex != 0)
{
StudentsClassSectionMapping.StudentsClassSectionMappingForm studentSectionMapping = new StudentsClassSectionMapping.StudentsClassSectionMappingForm();
studentSectionMapping.ssClassId = h;
studentSectionMapping.ssStudentId = studentList.ssStudentId;
studentSectionMapping.ssStudentId = long.Parse(d.SelectedItem.Value);
StudentsClassSectionMapping.addSectionStudentMapping(studentSectionMapping);
}
else
{
StudentsClassSectionMapping.StudentsClassSectionMappingForm studentSectionMapping = new StudentsClassSectionMapping.StudentsClassSectionMappingForm();
studentSectionMapping.ssClassId = h;
studentSectionMapping.ssStudentId = 0;
studentSectionMapping.ssStudentId = 0;
StudentsClassSectionMapping.addSectionStudentMapping(studentSectionMapping);
}
}
}
}
It get vanished/disappear because you added it dynamically on page. If you want it back or want to reserver control which is dynamically created you need to recreate again and need to add dynamically.
Here is good example of how you can do it : How to create controls dynamically in ASP.NET and retrieve values from it

Issue of addition of blank row in gridview

I have fetched data from db table, bound it to gridview and then export data from gridview to excel. It works fine.
But when I added a row at the top of gridview in databound event by using below code:
protected void gvReports_DataBound(object sender, EventArgs e)
{
if (gvReports.Rows.Count > 0)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
int count = gvReports.HeaderRow.Cells.Count;
TableHeaderCell cell = new TableHeaderCell();
cell.BorderWidth = 0;
cell.Text = "Commodity " + ddlCommMFArrival.SelectedItem.Text;
cell.ColumnSpan = count - 2;
row.Controls.Add(cell);
row.BackColor = ColorTranslator.FromHtml("#f5fafd");
gvReports.HeaderRow.Parent.Controls.AddAt(0, row);
}
}
Code to export Gridview to Excel:
protected void btnExport_Click(object sender, EventArgs e)
{
for (int i = 0; i < gvReports.Rows.Count; i++)
{
for (int j = 0; j < gvReports.Rows[i].Cells.Count; j++)
{
if (gvReports.Rows[i].Cells[j].Text == "NA")
{
gvReports.Rows[i].Cells[j].HorizontalAlign = HorizontalAlign.Right;
}
}
}
gvReports.HeaderRow.Cells[1].Visible = false;
gvReports.HeaderRow.Cells[2].Visible = false;
string filename = string.Empty;
int ddlselect = Convert.ToInt32(ddlCommMFArrival.SelectedValue);
if (ddlselect == 1)
{
filename = "MarketFee" + DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "") + "";
}
else if (ddlselect == 2)
{
filename = "Commodity Arrival" + DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "") + "";
}
//Export gridview data into MS Excel
blExportToExcel blExport = new blExportToExcel();
//Export gridview data into MS Excel
blExport.ExportGridViewToExcel(gvReports, this, filename);
}
public void ExportGridViewToExcel(GridView grv, System.Web.UI.Page pg, string fileName)
{
grv.AllowPaging = false;
pg.Response.Clear();
pg.Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".xls");
pg.Response.Charset = "";
pg.Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
grv.RenderControl(htmlWrite);
pg.Response.Write(stringWrite.ToString());
pg.Response.End();
grv.AllowPaging = true;
}
Then it adds a blank row at position 0 as well as in excel (export data from gridview to excel) and truncates the last row from gridview. Anyone knows what is the issue?
Try moving your HeaderRow addition logic out of DataBound and into RowCreated. Add this to the GridView declaration:
OnRowCreated="gvReports_RowCreated"
And then this is the RowCreated (note the DataControlRowState.Insert):
protected void gvReports_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
int count = e.Row.Cells.Count;
TableHeaderCell cell = new TableHeaderCell();
cell.BorderWidth = 0;
cell.Text = "blah";
cell.ColumnSpan = count - 2;
row.Controls.Add(cell);
row.BackColor = ColorTranslator.FromHtml("#f5fafd");
gvReports.Controls[0].Controls.AddAt(0, row);
}
}

How to ReCreate Dynamically generated webcontrols which has an On_click event

Current scenario: Main DDL of Decimal datatype input selection generates a new DDL. Upon input selection from new DDL it generates two labels and two textboxes with + button.
Current Issue: If i click the + button the recently generated dynamic web controls are hiding. How to avoid the hiding of controls and generate them continuously on every + button click event
My C# Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownLists();
}
else
{
if (!String.IsNullOrEmpty(DropDownList5.SelectedValue))
{
if (DropDownList5.SelectedValue == "decimal")
{
createdynamiccontrols_decimal();
}
}
}
}
protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void createdynamiccontrols_decimal()
{
int i = DropDownList5.SelectedIndex;
++i;
TableRow row = new TableRow();
row.ID = "TableRow_" + i.ToString();
TableCell cell1 = new TableCell();
DropDownList Range_DDL_Decimal = new DropDownList();
Range_DDL_Decimal.ID = "RandeDDL_Decimal" + i.ToString();
Range_DDL_Decimal.Items.Insert(0, new ListItem("--Select--", "--Select--"));
Range_DDL_Decimal.Items.Insert(1, new ListItem("Equal", "Equal"));
Range_DDL_Decimal.Items.Insert(2, new ListItem("NotEqual", "NotEqual"));
Range_DDL_Decimal.Items.Insert(3, new ListItem("greater than", "greater than"));
Range_DDL_Decimal.Items.Insert(4, new ListItem("lesser than", "lesser than"));
Range_DDL_Decimal.Items.Insert(5, new ListItem("greater than or equal to", "greater than or equal to"));
Range_DDL_Decimal.Items.Insert(6, new ListItem("lesser than or equal to", "lesser than or equal to"));
Range_DDL_Decimal.Items.Insert(7, new ListItem("Contains", "Contains"));
Range_DDL_Decimal.Items.Insert(8, new ListItem("Is Null", "Is Null"));
Range_DDL_Decimal.Items.Insert(9, new ListItem("Is Not Null", "Is Not Null"));
Range_DDL_Decimal.Items.Insert(10, new ListItem("Between", "Between"));
Range_DDL_Decimal.AutoPostBack = true;
Range_DDL_Decimal.SelectedIndexChanged += new System.EventHandler(Range_DDL_Decimal_SelectedIndexChanged);
cell1.Controls.Add(Range_DDL_Decimal);
//// Add the TableCell to the TableRow
row.Cells.Add(cell1);
dynamic_filter_table.Rows.Add(row);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
protected void Range_DDL_Decimal_SelectedIndexChanged(object sender, EventArgs e)
{
int j = DropDownList5.SelectedIndex;
++j;
TableRow rowtwo;
rowtwo = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
TableCell cell3 = new TableCell();
TextBox tb1 = new TextBox();
TextBox tb2 = new TextBox();
Label lbl1 = new Label();
Label lbl2 = new Label();
// Set a unique ID for each TextBox added
tb1.ID = "lowerbound_" + j.ToString();
tb2.ID = "upperbound_" + j.ToString();
lbl1.Text = "LowerBound:";
lbl1.Font.Size = FontUnit.Point(10);
lbl1.Font.Bold = true;
lbl1.Font.Name = "Arial";
lbl2.Text = "UpperBound:";
lbl2.Font.Size = FontUnit.Point(10);
lbl2.Font.Bold = true;
lbl2.Font.Name = "Arial";
Button addmore = new Button();
addmore.ID = "Button_Decimal" + j.ToString();
addmore.Text = "+";
addmore.Click += new System.EventHandler(Addmore_click);
**//If this button is clicked the Dynamic controls are vanished**
cell1.Controls.Add(lbl1);
cell1.Controls.Add(tb1);
cell2.Controls.Add(lbl2);
cell2.Controls.Add(tb2);
cell3.Controls.Add(addmore);
rowtwo.Cells.Add(cell1);
rowtwo.Cells.Add(cell2);
rowtwo.Cells.Add(cell3);
dynamic_filter_table.Rows.Add(rowtwo);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
protected void Addmore_click(object sender, EventArgs e)
{
**//Generate dynamic controls on every click of + button
//How to procced**
}
protected void Page_PreInit(object sender, EventArgs e)
{
}
There are not hiding, you have to recreate the dynamically created controls on every request.
It has been a while, but I think you have to create the dynamic controls in the Page_Init event for them to be included in the view-state.
Some sources

Categories