Finding dynamically added server control and use it's HTML - c#

I'm trying to get Text from a dynamically craeted server textbox.
I'm just checking by getting the text into another textbox I placed in the aspx file, but all I get is always an empty string..
(I also tried another method that is enclosed in remark, but it doesn't work either)
Here's the code behind:
public partial class Product_list : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
create_table();
}
protected void create_table()
{
DBServices db1=new DBServices();
List<Product> list1 = db1.ReadProducts();
int id_number=1;
int id_numer2 = 7;
int id_number3 = 13;
Table tbl = new Table();
tbl.ID = "tbl1";
this.Controls.Add(tbl);
foreach (Product p1 in list1)
{
TableRow rw = new TableRow();
rw.ID = Convert.ToString(id_numer2);
TableCell cell1 = new TableCell();
cell1.Text = p1.Name;
TableCell cell2 = new TableCell();
Image img = new Image();
img.ImageUrl = p1.ImagePath;
img.Height = 50;
img.Width = 50;
cell2.Controls.Add(img);
TableCell cell3 = new TableCell();
cell3.ID = Convert.ToString(id_number3);
TextBox textbox1 = new TextBox();
textbox1.ID = Convert.ToString(id_number);
cell3.Controls.Add(textbox1);
rw.Controls.Add(cell1);
rw.Controls.Add(cell2);
rw.Controls.Add(cell3);
tbl.Controls.Add(rw);
id_number++;
id_numer2++;
id_number3++;
}
}
void save_list()
{
List<Product> Items_list = new List<Product>();
//TextBox aControl =Page.FindControl("1") as TextBox;
/var tbl1 = this.Page.FindControl("tbl1") as Table;
var tr = tbl1.FindControl("7") as TableRow;
var td = tr.FindControl("13") as TableCell;
var txt = td.FindControl("1") as TextBox;
txt1.Value = txt.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
save_list();
}
}
and here is the aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Product_list.aspx.cs" Inherits="Product_list" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script runat=server>
public override void VerifyRenderingInServerForm(Control control)
{
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="header">
<h1>Items List</h1>
</div>
<div id="prod_table" runat="server"></div>
<div>
<input type="text" runat="server" id="txt1" />
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
</div>
</form>
</body>
</html>

You should understand that you recreate your table on every post to the server. So, you cannot rely on data from your dynamic table, because it would be lost after each posting. My suggestion is to keep this value in permanent input control with a type "hidden". Then on button click event just get this value and assign it to a textbox.

Related

How to use asp:Repeater tag and then use data-binding expressions without declare Microsoft SQL Server database?

How to use asp:Repeater tag and then use data-binding expressions without declare Microsoft SQL Server database?
Because I ask question at link but I learn asp:Repeater tag article have to declare Microsoft SQL Server database in DataBind article.
I ask question to solve "How to use asp:Repeater tag and then use data-binding expressions without declare Microsoft SQL Server database."
Good news : I have answer to use asp:Repeater tag and then use data-binding expressions without declare Microsoft SQL Server database.
My full source code.
https://github.com/doanga2007/CheckLoopQR
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckLoopQR.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.6.4.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(window).load(function(){
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:CheckBox ID="checkAll" runat="server" Font-Size="Large"/><asp:Label id="checkTextAll" runat="server" Font-Size="Large"></asp:Label><br /><br />
<asp:CheckBoxList ID="CheckBox1" runat="server" Border="1"
BorderColor="LightGray" Font-Size="Large"></asp:CheckBoxList>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing.Common;
using ZXing;
using ZXing.QrCode;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace CheckLoopQR
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.checkTextAll.Text = " Check All";
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
long num = Convert.ToInt64(code);
int i;
for (i = 1; i < 4; i++)
{
num += i;
CheckBox1.Items.Add(new ListItem(" " + num));
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
if (CheckBox1.SelectedItem == null)
{
Response.Redirect("Default.aspx");
}
string[] texture = { "Selected Item Text1 : ", "Selected Item Text2 : ", "Selected Item Text3 : " };
int a = 0;
foreach (ListItem listItem in CheckBox1.Items)
{
if (listItem.Selected)
{
a++;
string code = listItem.Text;
CheckBox1.Visible = false;
checkAll.Visible = false;
checkTextAll.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
Label lblvalues = new Label();
lblvalues.Text += texture[a-1] + listItem.Text;
lblvalues.Font.Size = FontUnit.Large;
Label lblvalues2 = new Label();
lblvalues2.Text += texture[a-1] + listItem.Text;
lblvalues2.Font.Size = FontUnit.Large;
Label lblvalues3 = new Label();
lblvalues3.Text += texture[a-1] + listItem.Text;
lblvalues3.Font.Size = FontUnit.Large;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues2);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues3);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
}
}
else
{
//do something else
}
}
}
}
}

How to replace a placeholder with a control in code behind?

I want to enable my users to create templates with placeholders like ##CreateLink## which should be replaced in code-behind by controls.
I know how to create controls in runtime but I have no idea how to replace the placeholder with these dynamically created controls.
How can I achieve this?
This is my .aspx code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="lit" runat="server" Text="This is my sample text. Here is my ##token## which should be replaced by my control in codebehind..."></asp:Literal>
</div>
</form>
</body>
</html>
And this is my codebehind:
public partial class WebForm1 : System.Web.UI.Page
{
private HyperLink lnk;
protected override void CreateChildControls()
{
base.CreateChildControls();
lnk = new HyperLink();
lnk.ID = "lnk";
lnk.NavigateUrl = "http://www.google.com";
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
}
}
Using another answer to guide me I worked out the following:
.aspx Markup
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="lit" runat="server" Text="This is my sample text. Here is my ##token## and my button ##button## which should be replaced by my control in codebehind..."></asp:Literal>
<p>this is a default button</p>
<asp:Button ID="btn2" runat="server" text="from asp.net" />
</div>
</form>
</body>
</html>
C# CodeBehind code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
private HyperLink lnk;
private Button btn;
protected override void CreateChildControls()
{
base.CreateChildControls();
lnk = new HyperLink();
lnk.ID = "lnk";
lnk.Text = "<b>Sample Link</b>";
lnk.NavigateUrl = "http://www.google.com";
btn = new Button();
btn.ID = "btn";
btn.Text = "button text";
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
StringBuilder sb = new StringBuilder();
HtmlTextWriter myWriter = new HtmlTextWriter(new System.IO.StringWriter(sb, System.Globalization.CultureInfo.InvariantCulture));
base.Render(myWriter);
myWriter.Flush();
string renderedHtml = sb.ToString();
renderedHtml = renderedHtml.Replace("##token##", RenderHTML(lnk));
renderedHtml = renderedHtml.Replace("##button##", RenderHTML(btn));
writer.Write(renderedHtml);
myWriter.Close();
sb.Clear();
}
private string RenderHTML(Control ctrl)
{
StringBuilder sb = new StringBuilder();
HtmlTextWriter myWriter = new HtmlTextWriter(new System.IO.StringWriter(sb, System.Globalization.CultureInfo.InvariantCulture));
ctrl.RenderControl(myWriter);
myWriter.Close();
return sb.ToString();
}
}
}
Use Render method
protected override void Render(HtmlTextWriter writer)
{
//Place replace logic
}
Update
protected override void Render(HtmlTextWriter writer)
{
MemoryStream stream = new MemoryStream();
StreamWriter memWriter = new StreamWriter(stream);
HtmlTextWriter myWriter = new HtmlTextWriter(memWriter);
base.Render(myWriter);
myWriter.Flush();
stream.Position = 0;
string renderedHtml = new StreamReader(stream).ReadToEnd();
renderedHtml = renderedHtml.Replace("##token##", "VALUE");
writer.Write(renderedHtml);
writer.Close();
myWriter.Close();
stream.Close();
}

Dynamically adding images using UpdatePanel

I'm trying to dynamically create images in a table but it seems like the UpdatePanel is not updating. I have the following code in my .aspx page.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="ViewTile.aspx.cs" Inherits="ViewTile" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body runat="server">
<form id="form1" runat="server">
<div>
<asp:Image ID="tileImg" runat="server"/>
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<table>
<asp:updatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="placeholder1"/>
</ContentTemplate>
</asp:updatePanel>
</table>
</div>
</form>
</body>
</html>
And then this this the aspx.cs page.
TableRow imageRow = new TableRow();
for (int rowItr = 0; rowItr < 3; rowItr++)
{
for (int colItr = 0; colItr < 4; colItr++)
{
System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image();
image.ImageUrl = "~/ShowTile.ashx?SheetId=" + SheetGUID + "&Scale=" + 3
+ "&XCoord=" + colItr + "&YCoord=" + rowItr;
placeholder1.Controls.Add(image);
TableCell imageCell = new TableCell();
imageCell.Controls.Add(image);
imageRow.Cells.Add(imageCell);
}
placeholder1.Controls.Add(imageRow);
imageRow.Cells.Clear();
}
I know for a fact that the image is being called correctly as I've outputted it manually using an image tag on the client. Any help would be great! Thanks
You need to add Table first, add rows to it and finally add table to placeholder1.Controls
Table tbl= new Table();
for (int rowItr = 0; rowItr < 3; rowItr++)
{
TableRow imageRow = new TableRow();
for (int colItr = 0; colItr < 4; colItr++)
{
System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image();
image.ImageUrl = "~/ShowTile.ashx?SheetId=" + SheetGUID + "&Scale=" + 3
+ "&XCoord=" + colItr + "&YCoord=" + rowItr;
TableCell imageCell = new TableCell();
imageRow.Cells.Add(imageCell);
}
tbl.Rows.Add(imageRow);
}
placeholder1.Controls.Add(tbl);
You Can Do this using javascript and Web Service.
Create a function that Call Web Service and fetch url of the image and append it into the update panel div

Problems with JavaScript for multi-upload

I'm trying to make a multi-file upload. with help from this blog, but is getting an error.
the code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Upload_Multiple_Files._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
var selectedFiles = '';
function ReceiveServerData(response) {
alert(response);
}
function uploadFile() {
var fileList = document.getElementById("fileDivBox").getElementsByTagName("INPUT");
for (i = 0; i < fileList.length; i++) {
selectedFiles += fileList[i].value + "|";
}
CallServer(selectedFiles, '');
}
function attachFile() {
var fu = document.createElement("INPUT");
fu.type = "file";
var br = document.createElement("<BR>");
document.getElementById("fileDivBox").appendChild(fu);
document.getElementById("fileDivBox").appendChild(br);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Attach a file
</div>
</form>
</body>
</html>
codebehind:
namespace Upload_Multiple_Files
{
public partial class _default : System.Web.UI.Page
{
public void RaiseCallbackEvent(string eventArgument)
{
string[] files = (eventArgument.TrimEnd('|')).Split('|');
WebClient client = new WebClient();
foreach (string file in files)
{
client.UploadFile("http://localhost:3850/FileServer.aspx", "POST", file);
}
}
protected void Page_Load(object sender, EventArgs e)
{
string path = #"C:\UploadedFiles\"; // server folder
string[] keys = Request.Files.AllKeys;
foreach (String key in keys)
{
HttpPostedFile file = Request.Files[key];
file.SaveAs(path + file.FileName);
}
}
}
}
the error occours in the line: br = document.createElement("<BR>");
where it says "unhandled exeption". I'm new to javascript thereby having no clue was wrong.
The document.CreateElement function will add the < > part of the tag for you. What your code is attempting to do is create an element of <<br>>, which is invalid. Call the method with just the tag name of BR:
br = document.CreateElement("BR");
This will create a <br> tag for you as you expect.

500 internal server error on hidden __viewstate of asp.net page

I am trying to post the data to cross domain. It works fine if the form is not using runat="server" and its giving 500 internal error while posting when the form is using runat="server".
Upon debugging, I identified that the problem is with auto generated __viewstate code on the page. Please find the below code.
Clientside HTML implementation:
<%# Page Language="C#" CodeFile="Sample.aspx.cs" Inherits="Sample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta charset="utf-8">
<title>Untitled Page</title>
<link href="FileUpload.css" rel="stylesheet" type="text/css" />
<script id="template-upload" type="text/x-tmpl">
</script>
<script id="template-download" type="text/x-tmpl">
</script>
<script src="../../test/FileUpload/jQueryv1.6.2.js"></script>
<script src="fileupload-js/jquery.ui.widget.js"></script>
<script src="fileupload-js/tmpl.min.js"></script>
<script src="fileupload-js/jquery.fileupload.js"></script>
<script src="fileupload-js/jquery.fileupload-ui.js"></script>
<script src="fileupload-js/locale.js"></script>
<script src="fileupload-js/main.js"></script>
</head>
<body>
<form id="fileupload" method="POST" runat="server">
<CCAB.Web:FileUpload runat="server"/>
</form>
</body>
</html>
Serverside code:
public partial class SaveFile : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
Response.AddHeader("Access-Control-Allow-Origin", "*")
if (Request.HttpMethod == "GET" || Request.HttpMethod == "HEAD")
{
Response.Write("GET Success");
}
else
{
for (int i = 0; i < Request.Files.Count; i++)
{
string filename = Request.Files[i].FileName;
Request.Files[i].SaveAs(#"\\dev2\\share$\\Anna\\test\\" + filename);
Response.Write(filename);
Response.Write("Success");
}
}
}
}
Could you please help me in how to ignore the hidden viewstate code from client side or ignore the response viewstate in server side.
Many Thanks
Anna
Try disabling view state by adding a line of code to your unload handler:
Page.EnableViewState = false;
see this MSDN page
I have found the solution for this problem. Please find below
public class BasePage : Page
{
private static string[] aspNetFormElements = new string[]
{
"__EVENTTARGET",
"__EVENTARGUMENT",
"__VIEWSTATE",
"__EVENTVALIDATION",
"__VIEWSTATEENCRYPTED",
};
protected override void Render(HtmlTextWriter writer)
{
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
string html = stringWriter.ToString();
int formStart = html.IndexOf("<form");
int endForm = -1;
if (formStart >= 0)
endForm = html.IndexOf(">", formStart);
if (endForm >= 0)
{
StringBuilder viewStateBuilder = new StringBuilder();
foreach (string element in aspNetFormElements)
{
int startPoint = html.IndexOf("<input type=\"hidden\" name=\"" + element + "\"");
if (startPoint >= 0 && startPoint > endForm)
{
int endPoint = html.IndexOf("/>", startPoint);
if (endPoint >= 0)
{
endPoint += 2;
string viewStateInput = html.Substring(startPoint, endPoint - startPoint);
html = html.Remove(startPoint, endPoint - startPoint);
viewStateBuilder.Append(viewStateInput).Append("\r\n");
}
}
}
if (viewStateBuilder.Length > 0)
{
viewStateBuilder.Insert(0, "\r\n");
html = html.Insert(endForm + 1, viewStateBuilder.ToString());
}
}
writer.Write(html);
}
}
Please find more info on this page : http://blogs.msdn.com/b/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx
Many Thanks
Anna

Categories