I have images displayed from a folder and with the help of the function below i am able to do just that.
private void LoadImages()
{
foreach (string strfile in Directory.GetFiles(Server.MapPath("~/Data")))
{
ImageButton imageButton = new ImageButton();
FileInfo fi = new FileInfo(strfile);
imageButton.ImageUrl = "~/Data/" + fi.Name;
imageButton.Height = Unit.Pixel(100);
imageButton.Style.Add("padding", "5px");
imageButton.Width = Unit.Pixel(100);
imageButton.Click += new ImageClickEventHandler(imageButton_Click);
Panel1.Controls.Add(imageButton);
}
}
Guys! i need to display the name of the image below the image. Help Please!
Wrap the ImageButton into a parent DIV element with the text label. A small table with two rows and 1 cell would work well also.
Example:
Table table = new Table();
TableRow row = new TableRow();
TableCell cell = new TableCell();
table.Controls.Add(row);
row.Controls.Add(cell);
cell.Controls.Add(imageButton);
row = new TableRow();
cell = new TableCell();
table.Controls.Add(row);
row.Controls.Add(cell);
cell.Text = "Image Text";
Related
I have added a hyperlink to my existing Table cells but I get the filmname twice. Also i want to add other table cells as hyperlinks like Directors, Actors and Filmyear. how do i do that?
My Table Cells below:
tc = GetTableCell(film.FilmName);
tr.Cells.Add(tc);
tc = GetTableCell(film.Directors[0].PersonName);
tr.Cells.Add(tc);
tc = GetTableCell(film.Actors[0].PersonName);
tr.Cells.Add(tc);
tc = GetTableCell(film.FilmYear);
tr.Cells.Add(tc);
My HyperLink code below:
HyperLink link = new HyperLink();
link.NavigateUrl = "https://www.imdb.com/title/tt4154756/";
link.Text = film.FilmName;
tc.Controls.Add(link);
tr.Cells.Add(tc);
Try this.
private void CreateTable()
{
Table table = new Table();
TableRow tr = new TableRow();
//film name
tr.Cells.Add(GetTableCell("Film Name"));
//director
tr.Cells.Add(GetTableCell("Director Name"));
//actor
tr.Cells.Add(GetTableCell("Actor Name"));
//film year
tr.Cells.Add(GetTableCell("Film Year"));
//film link
HyperLink link = new HyperLink();
link.NavigateUrl = "https://www.imdb.com/title/tt4154756/";
link.Text = "Film Name";
tr.Cells.Add(GetTableCell(link));
table.Rows.Add(tr);
}
//returns new table cell with text content
private TableCell GetTableCell(string text)
{
TableCell tc = new TableCell();
tc.Text = text;
return tc;
}
//returns new table cell with hyperlink
private TableCell GetTableCell(HyperLink link)
{
TableCell tc = new TableCell();
tc.Controls.Add(link);
return tc;
}
i'm creating dynamic checkbox and textbox Control on page Load and i want to get the values of control on button click but we are not able to find out
here is my Dynamic control Code
DataTable dt = new DataTable();
da.Fill(dt);
var Count = dt.Rows.Count;
if (Count > 0)
{
TableHeaderRow thr = new TableHeaderRow();
TableHeaderCell cellheader = new TableHeaderCell();
TableHeaderCell thc = new TableHeaderCell();
TableHeaderCell thcode = new TableHeaderCell();
TableHeaderCell thcReason = new TableHeaderCell();
thc.Text = "Select";
thc.CssClass = "pd";
thcode.Text = "Description";
thcode.CssClass = "pdlbl";
thcReason.Text = "Reason";
thcReason.CssClass = "thcReason";
thr.Cells.Add(thc);
thr.Cells.Add(thcode);
thr.Cells.Add(thcReason);
tbl.Rows.Add(thr);
for (int i = 0; i < Count; i++)
{
TableRow tr = new TableRow();
TableCell tc = new TableCell();
TableCell tc1 = new TableCell();
TableCell tc2 = new TableCell();
CheckBox chk = new CheckBox();
Label lbl = new Label();
TextBox txtBox = new TextBox();
txtBox.ID = "txt" + i.ToString();
txtBox.TextMode = TextBoxMode.MultiLine;
chk.ID = "chk" + i.ToString();
lbl.ID = "lbl" + i.ToString();
lbl.Text = dt.Rows[i]["DESCRIPTION"].ToString();
tc.Controls.Add(chk);
tc.Width = new Unit("5px");
tc.CssClass = "chkcntrl";
tc1.Controls.Add(lbl);
tc1.Width = new Unit("75%");
tc2.Controls.Add(txtBox);
tc2.Width = new Unit("20%");
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
tbl.Rows.Add(tr);
}
tbl.EnableViewState = true;
ViewState["tbl"] = true;
}
after create the control i want to find out the values
my code are below
foreach (TableRow tr in tbl.Controls)
{
string str_Confirmed = string.Empty;
string str_Description = string.Empty;
string str_Reason = string.Empty;
foreach (TableCell tc in tr.Controls)
{
if (tc.Controls[0] is CheckBox)
{
if (((CheckBox)tc.Controls[0]).Checked == true)
{
str_Confirmed = "Y";
}
else
{
str_Confirmed = "N";
}
}
if (tc.Controls[1] is Label)
{
string txt = string.Empty;
str_Description = ((Label)tc.Controls[1]).Text;
}
if (tc.Controls[2] is TextBox)
{
str_Reason = ((TextBox)tc.Controls[2]).Text;
//Response.Write(((TextBox)tc.Controls[0]).Text);
}
}
but when i will execute this code we are getting the Specified argument was out of the range of valid values. Parameter name: index please any one can tell me where am wrong
You have different table cells for each control you are adding.
tc has the checkbox control
tc1 has the label control
EDIT: A few other changes were needed to your code.
You were iterating through, tbl.Controls not tbl.Rows
You were iterating through tr.Controls not tr.Cells
The first table row you add is the header information that has no
controls so added check that controls.count() is greater than 0
Hope this helps
foreach (TableRow tr in tbl.Rows)
{
string str_Confirmed = string.Empty;
string str_Description = string.Empty;
string str_Reason = string.Empty;
foreach (TableCell tc in tr.Cells)
{
if (tc.Controls.Count > 0)
{
if (tc.Controls[0] is CheckBox)
{
if (((CheckBox)tc.Controls[0]).Checked == true)
{
str_Confirmed = "Y";
}
else
{
str_Confirmed = "N";
}
}
else if (tc.Controls[0] is Label)
{
string txt = string.Empty;
str_Description = ((Label)tc.Controls[1]).Text;
}
else if (tc.Controls[0] is TextBox)
{
str_Reason = ((TextBox)tc.Controls[2]).Text;
//Response.Write(((TextBox)tc.Controls[0]).Text);
}
}
}
}
Im creating a table and have added a few controls to it dynamically but the ID im assigning to these controls doesn't seem to be the same when i inspect them with firebug they seem to get a prefix so trying to do FindControls("controlname")when posting the page im not having much joy. example of the controls id: ctl00_ContentPlaceHolder1_Monday_Normal_Small but then adding that prefix to the control name not having much joy either.
Any suggestions would be much appreciated, thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
CreateMenu();
}
public void CreateMenu()
{
Table table = new Table();
table.Attributes.Add("class", "table table-bordered");
Label lbl = new Label();
TableRow tr = new TableRow();
TableCell tc = new TableCell();
TableHeaderCell thc = new TableHeaderCell();
lbl.Text = "Day";
thc.Controls.Add(lbl);
tr.Cells.Add(thc);
thc = new TableHeaderCell();
lbl = new Label();
lbl.Text = "Meal";
thc.Controls.Add(lbl);
tr.Cells.Add(thc);
thc = new TableHeaderCell();
lbl = new Label();
lbl.Text = "Normal";
thc.Controls.Add(lbl);
tr.Cells.Add(thc);
thc = new TableHeaderCell();
lbl = new Label();
lbl.Text = "No Carb";
thc.Controls.Add(lbl);
tr.Cells.Add(thc);
table.Rows.Add(tr);
for(int i=0;i<5;i++)
{
tr = new TableRow();
tc = new TableCell();
lbl = new Label();
lbl.Text = "<h1 style='text-align:right;'>" + GetDay(i) + "</h1>";
tc.Controls.Add(lbl);
tr.Cells.Add(tc);
tc = new TableCell();
lbl = new Label();
lbl.Text = GetMeal(i);
tc.Controls.Add(lbl);
tr.Cells.Add(tc);
for (int j = 0; j <= 1; j++)
{
tc = new TableCell();
Table dropdowntable = new Table();
TableRow tr2 = new TableRow();
TableCell tc2 = new TableCell();
for (int k = 0; k <= 2; k++)
{
DropDownList ddl = new DropDownList();
ddl.ID = GetDay(i) + "_" + GetType(j) + "_" + GetSize(k);
ddl.DataSource = numbers;
ddl.DataBind();
tc2.Controls.Add(ddl);
}
tr2.Cells.Add(tc2);
dropdowntable.Rows.Add(tr2);
tc.Controls.Add(dropdowntable);
tr.Cells.Add(tc);
}
table.Rows.Add(tr);
}
tableplaceholder.Controls.Add(table);
}
Ive changed the ClientIDMode of the ddl controls and no prefix but this doesnt seem to solve my problem, so i have a submit button at the bottom of my page and calling its click method trying this
DropDownList ddl = (DropDownList)FindControl(controlName);
try
{
int num = Convert.ToInt32(ddl.SelectedValue);
}
catch(Exception ex)
{
return 0;
}
return 0;
But no luck any ideas?
To have same Id while inspecting in Firebug you should use one of the from the below.
Set Clientmode of dropdown to Static (so that it will have same ID in client side.
ddl.ClientIDMode = ClientIDMode.Static;
2.Use ClientId property in javascript to get the exact ID of the control.
var ddlValue = document.getElementById("<% ddl.ClientID %>");
Try setting the ClientIDMode = Static, for the control your are adding as explained in MSDN
Hope this helps!
I realized the issue i was having was when trying to FindControl() i was passing the control's ID and not the controls name, this resolved my issue.
I have following code that I am using for export to excel of a gridview. I am adding the gridview rows into System.Web.UI.WebControls.Table. Now, I need to apply background color to the header and data rows in the exported excel (There are two header rows).
I tired the following. It is not providing the desired result.
Issues of current solution
One header row does not have background color
Coloring is applied to cells that does not have data (cells “H”, “I”, etc.)
How can we correct it?
Note: I am trying to learn the export feature. So, please don't suggest to use any third party controls. I am just exploring all features of this approach.
I am adding the header grouping to the original gridview using following code.
protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
System.Text.StringBuilder sbNewHeader = new StringBuilder();
sbNewHeader.AppendFormat(" </th>" +
"<th colspan='2' class='tableColGroupAssociate'>Associate Info <a href='#' class='associateHide'> Hide </a> </th>" +
"<th colspan='2' class='tableColGroupTransaction'>Financial Info <a href='#' class='financialHide'> Hide </a> </th>" +
"<th colspan='2' class='tableColGroupDailyTax'>Tax Info <a href='#' class='dailyTaxHide'> Hide </a> </th>"
+ "</tr>");
sbNewHeader.AppendFormat("<tr class='{0}'><th>{1}", this.gvCustomers.HeaderStyle.CssClass, e.Row.Cells[0].Text);
e.Row.Cells[0].Text = sbNewHeader.ToString();
}
}
Complete Code
public static void Export(GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MyExcelFile.xls"));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter stringWriter = new StringWriter())
{
using (HtmlTextWriter tetxWriter = new HtmlTextWriter(stringWriter))
{
System.Web.UI.WebControls.Table tableControl = new Table();
tableControl.GridLines = gv.GridLines;
//Before the next step - we can remove any controls inside the gridview and replace with literal control
// Add the header row to the table
if (gv.HeaderRow != null)
{
TableRow tableRow = gv.HeaderRow;
tableRow.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Orange";
tableControl.Rows.Add(gv.HeaderRow);
}
// Add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
TableRow tableRow = row;
tableRow.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Yellow";
tableControl.Rows.Add(row);
}
// Render the table into the htmlwriter
tableControl.RenderControl(tetxWriter);
// Render the htmlwriter into the response
HttpContext.Current.Response.Write(stringWriter.ToString());
HttpContext.Current.Response.End();
}
}
}
EDIT
Based on comment from Ankit, I tried the following; still the result is not as expected.
if (gv.HeaderRow != null)
{
TableRow tableRow = gv.HeaderRow;
foreach (TableCell cell in tableRow.Cells)
{
cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Orange";
}
tableControl.Rows.Add(gv.HeaderRow);
}
If you want more control over how your excel files are written take a look at ClosedXML
Adding a table is as simple as
var wb = new XLWorkbook();
wb.Worksheets.Add(myDataTable);
wb.SaveAs("MySheet.xlsx");
Using the API you can code like this:
var rngTable = ws.Range("B2:F6");
rngTable.FirstCell().Style
.Font.SetBold()
.Fill.SetBackgroundColor(XLColor.CornflowerBlue)
.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
I figured a way to do it... For the benefit of others I will post it here:
References:
ASP.NET Excel export encoding problem
Other Note: When a new Table is created TableSection can be used to define header
newRow.TableSection = TableRowSection.TableHeader;
CODE
//Changed the logic used for adding dynamic header for HTML rendering:
protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow newHeaderRow = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
TableCell cell1 = new TableHeaderCell();
cell1.ColumnSpan = 1; //e.Row.Cells.Count;
cell1.Text = "";
TableCell cell2 = new TableCell();
cell2.ColumnSpan = 2;
cell2.Text = "One";
TableCell cell3 = new TableCell();
cell3.ColumnSpan = 2;
cell3.Text = "Two";
TableCell cell4 = new TableCell();
cell4.ColumnSpan = 2;
cell4.Text = "Three";
newHeaderRow.Cells.Add(cell1);
newHeaderRow.Cells.Add(cell2);
newHeaderRow.Cells.Add(cell3);
newHeaderRow.Cells.Add(cell4);
((GridView)sender).Controls[0].Controls.AddAt(0, newHeaderRow);
}
if (e.Row.RowType == DataControlRowType.Header)
{
//System.Text.StringBuilder sbNewHeader = new StringBuilder();
//sbNewHeader.AppendFormat(" </th>" +
// "<th colspan='2' class='tableColGroupAssociate'>Associate Info <a href='#' class='associateHide'> Hide </a> </th>" +
// "<th colspan='2' class='tableColGroupTransaction'>Financial Info <a href='#' class='financialHide'> Hide </a> </th>" +
// "<th colspan='2' class='tableColGroupDailyTax'>Tax Info <a href='#' class='dailyTaxHide'> Hide </a> </th>"
// + "</tr>");
//sbNewHeader.AppendFormat("<tr class='{0}'><th>{1}", this.gvCustomers.HeaderStyle.CssClass, e.Row.Cells[0].Text);
//e.Row.Cells[0].Text = sbNewHeader.ToString();
}
}
//Export Logic - Applied similar logic once again
public static void Export(GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MyExcelFile.xls"));
HttpContext.Current.Response.ContentType = "application/ms-excel";
//Response.ContentEncoding = System.Text.Encoding.Unicode;
//Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
using (StringWriter stringWriter = new StringWriter())
{
using (HtmlTextWriter tetxWriter = new HtmlTextWriter(stringWriter))
{
System.Web.UI.WebControls.Table tableControl = new Table();
tableControl.GridLines = gv.GridLines;
// Add the header row to the table
if (gv.HeaderRow != null)
{
ReplaceControlForExport(gv.HeaderRow);
#region Dynamic Frrst Header Row
TableRow newRow = new TableRow();
TableCell cell1 = new TableHeaderCell();
cell1.ColumnSpan = 1;
cell1.Text = "";
TableCell cell2 = new TableCell();
cell2.ColumnSpan = 2;
cell2.Text = "One";
TableCell cell3 = new TableCell();
cell3.ColumnSpan = 2;
cell3.Text = "Two";
TableCell cell4 = new TableCell();
cell4.ColumnSpan = 2;
cell4.Text = "Three";
newRow.Cells.Add(cell1);
newRow.Cells.Add(cell2);
newRow.Cells.Add(cell3);
newRow.Cells.Add(cell4);
foreach (TableCell cell in newRow.Cells)
{
cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Purple";
}
tableControl.Rows.Add(newRow);
#endregion
TableRow originalHeaderRow = gv.HeaderRow;
foreach (TableCell cell in originalHeaderRow.Cells)
{
cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Orange";
}
tableControl.Rows.Add(originalHeaderRow);
}
// Add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
ReplaceControlForExport(row);
TableRow tableRow = row;
foreach (TableCell cell in tableRow.Cells)
{
cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Yellow";
}
tableControl.Rows.Add(row);
}
// Render the table into the htmlwriter
tableControl.RenderControl(tetxWriter);
// Render the htmlwriter into the response
HttpContext.Current.Response.Write(stringWriter.ToString());
HttpContext.Current.Response.End();
}
}
}
private static void ReplaceControlForExport(Control mainControlElement)
{
for (int i = 0; i < mainControlElement.Controls.Count; i++)
{
Control currentControl = mainControlElement.Controls[i];
if (currentControl is LinkButton)
{
mainControlElement.Controls.Remove(currentControl);
mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as LinkButton).Text));
}
else if (currentControl is ImageButton)
{
mainControlElement.Controls.Remove(currentControl);
mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as ImageButton).AlternateText));
}
else if (currentControl is HyperLink)
{
mainControlElement.Controls.Remove(currentControl);
mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as HyperLink).Text));
}
else if (currentControl is DropDownList)
{
mainControlElement.Controls.Remove(currentControl);
mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as DropDownList).SelectedItem.Text));
}
else if (currentControl is CheckBox)
{
mainControlElement.Controls.Remove(currentControl);
mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as CheckBox).Checked ? "True" : "False"));
}
//Recursive Call
if (currentControl.HasControls())
{
ReplaceControlForExport(currentControl);
}
}
}
Can anyone tell me how to dynamically create thead tbody tags in my c# code?
private void MakeTable()
{
Table tb = new Table();
TableRow tr = new TableRow();
TableCell td = new TableCell();
td.Text="hello world";
tr.Cells.Add(td);
tb.Rows.Add(tr);
}
Thanks
Here a sample code that creates a THead, TBody and TFooter.
You can basically always use the TableRow object just reset the TableSection property.
Table table = new System.Web.UI.WebControls.Table();
TableRow tableRow;
TableCell tableCell;
tableRow = new TableRow();
tableRow.TableSection = TableRowSection.TableHeader;
tableCell = new TableCell();
tableCell.Text = "HEADER";
tableRow.Cells.Add(tableCell);
table.Rows.Add(tableRow);
tableRow = new TableRow();
tableRow.TableSection = TableRowSection.TableBody;
tableCell = new TableCell();
tableCell.Text = "BODY";
tableRow.Cells.Add(tableCell);
table.Rows.Add(tableRow);
tableRow = new TableRow();
tableRow.TableSection = TableRowSection.TableFooter;
tableCell = new TableCell();
tableCell.Text = "FOOTER";
tableRow.Cells.Add(tableCell);
table.Rows.Add(tableRow);
plhTest.Controls.Add(table);
Although I would suggest building the table in direct html and appending to page.
TableRow is basically tbody.
To make a thead section, use the TableHeaderRow class instead of a TableRow class.
(There is also, btw, TableFooterRow if you want to implement tfoot.
var row = new TableHeaderRow() { TableSection = TableRowSection.TableHeader };
table.Rows.Add(row);
should do the trick