How to Create new div for each loop - c#

I am using asp.net with c# with Master Page. I was trying to create new div for each loop in the while to be able to make the designee as i want. Is there any way that i can do this Or is there any other way to do if from my aspx.cs only?
aspx.cs :
protected void Page_Load(object sender, EventArgs e)
{
while (Reader.Read())
{
Response.Write("<div id=test >");
Response.Write(Reader.GetString(3)+" ");
Response.Write(Reader.GetString(10) + "<br />");
Response.Write("<a href='Info.aspx?param=" + Reader.GetString(0) + "' target='_blank'>" + "More..." + "</a>");
Response.Write( "<br />");
Response.Write("");
Response.Write("</div>");
//TextBox1.Text = Reader.GetString(3);
//TextBox2.Text = Reader.GetString(10);
}
}
aspx :
<%# Page Title="" Language="C#" MasterPageFile="~/MainDesigne.Master" AutoEventWireup="true" CodeBehind="MobilePageRouteDoc.aspx.cs" Inherits="WebApplication2.MobilePageRoteDoc" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js">
</asp:ScriptReference>
<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js">
</asp:ScriptReference>
<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js">
</asp:ScriptReference>
</Scripts>
</telerik:RadScriptManager>
<link href="Assets/Css/mobile.css" rel="stylesheet" />
<telerik:RadDropDownList ID="RadDropDownList1" runat="server" OnSelectedIndexChanged="RadDropDownList1_SelectedIndexChanged">
</telerik:RadDropDownList>
<div id="test">
</div>
</asp:Content>

You could assign your <div id="test"> attribute runat="server" like this:
<div runat="server" id="test">
Then you can access it in your code behind:
test.InnerHtml = "your html here";
So basically first create your html(the multiple divs) in a loop, then add it to the 'test' div. Also I'd suggest you keep id of every element you create in your loop unique and don't forget to add double quotes... id="test1", id="test2", Here is your modified code:
protected void Page_Load(object sender, EventArgs e)
{
string html = "";
int i = 0;
while (Reader.Read())
{
html+= "<div id=\"test" + i + "\">";
html+= Reader.GetString(3) + " ";
html+= Reader.GetString(10) + "<br />";
html+= "<a href='Info.aspx?param=" + Reader.GetString(0) + "' target='_blank'>" + "More..." + "</a>";
html+= "<br />";
html+= "</div>";
i++;
}
test.InnerHtml = html;
}

If you want to add <div> you may follow this using HtmlGenericControl which can generate html
HtmlGenericControl div = new HtmlGenericControl();
div.ID = "AnyDivID";
div.TagName = "div";
div.Attributes["class"] = "YourClassName";
div.InnerText = string.Format("Inner text= {0} ;", "YourInnerText");
form1.Controls.Add(div);

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
}
}
}
}
}

load codebehind Gridview dynamically

I am generating this tags (IT,Marketing....) dynamically(codebehind) from the sql using linq to sql.
And when you click on any of the the tabs it will show the gridview as per table created in database.
But the gridview binding is done during page_load event, so everything is generated during page_load, now when you click any of the blue tabs , it will show you pre-generated gridviews.
Now i want to generate or load gridviews when i clck on [+] sign of any of the tabs and not during the page load
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div id="CONTAINER" onclick="">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="clickable mfiles" onclick="showHide('subm');changesign('signm');">
<span id="signm" class="plusMinus">[+]</span><span> M-Files<br />
</span>
</div>
<div id="subm">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</form>
<script>
function showHide(id) {
__doPostBack('UpdatePanel1', id);
var el = document.getElementById(id);
//if (el && el.style.display == 'block') {
// el.style.display = 'none';
//}
//else {
// el.style.display = 'block';
//}
}
function changesign(id1) {
var xy = document.getElementById(id1);
if (xy.innerHTML == "[-]") {
xy.innerHTML = "[+]";
}
else {
xy.innerHTML = "[-]";
}
}
</script>
banckend code:
protected void Page_Load(object sender, EventArgs e)
{
CONTACT_INFODataContext context = new CONTACT_INFODataContext("Data Source=BPM-IT116;Initial Catalog=FORM_GET;Persist Security Info=True;User ID=spreader;Password=Red_Sky");
var depts = context.spi_GetNoOfDept();
PlaceHolder1.Controls.Clear();
int i = 1;
foreach (spi_GetNoOfDeptResult dept in depts)
{
Literal div = new Literal();
Contact deptinfo = new Contact();
deptinfo.NAME_LAST = dept.DEPT_NAME;
deptinfo.DEPT_ID = dept.DEPT_ID.ToString();
div.Text = "<div class=\"even clickable\" onclick=\"showHide('sub" + dept.DEPT_ID + "');changesign('sign" + dept.DEPT_ID + "');\">";
div.Text += "<span id=\"sign" + dept.DEPT_ID + "\">[+]</span><span>" + dept.DEPT_NAME + "</span>";
div.Text += "</div>";
div.Text += "<div id=\"sub" + dept.DEPT_ID + "\" style=\"margin-left:15px ;\">";
//GridView gd = CreateDynamicTable(dept.DEPT_ID);
i++;
PlaceHolder1.Controls.Add(div);
PlaceHolder1.Controls.Add(new LiteralControl("</div>"));
}
private GridView CreateDynamicTable(int x)
{
GridView gd = new GridView();
gd.ID = "grd" + x;
gd.AlternatingRowStyle.CssClass = "altrowstyle1";
gd.RowStyle.CssClass = "rowstyle1";
gd.HeaderStyle.CssClass = "grdhdr";
gd.GridLines = GridLines.None;
List<Contact> contacts = new List<Contact>();
CONTACT_INFODataContext context = new CONTACT_INFODataContext("Data Source=BPM-IT116;Initial Catalog=FORM_GET;Persist Security Info=True;User ID=spreader;Password=Red_Sky");
var persons = context.spi_GetContacts();
var items = context.spi_GetDept(x);
var depts = context.spi_GetNoOfDept();
foreach (spi_GetDeptResult item in items)
{
Contact contact = new Contact();
contact.NAME_LAST = item.NAME_LAST;
contact.NAME_FIRST = item.NAME_FIRST;
contact.PHONE_CELL = item.PHONE_CELL;
contact.ADDRESS = item.ADDRESS;
contact.APT = item.APT;
contact.DEPT_ID = item.DEPT_ID.ToString();
contact.DEPT_NAME = item.DEPT_NAME;
contacts.Add(contact);
//ddl_db.Items.Add(new ListItem(person.NAME_FIRST));
}
gd.CssClass = "gdmain";
gd.DataSource = contacts;
gd.DataBind();
return gd;
}
If you use a Multiview control for your tab container then you should be able to bind your code to load the Gridview to the ActiveViewChanged event and change your ActiveViewIndex property for that Multiview when your users navigate between your tabs.

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

Getting the rewritten value of a contentEditable tag

in my code i want to set a tag with values from a .mdb database (oleDb) and when the user registers as an administrator i add the contentEditable=true attribute to the parts i want him to be able to edit. when he is done he will hit a 'save' button and the code behind will update the new value into the database.
here is the code: (Admin.LogIn(,); also returns true if the user registered as an admin)
<%# Page Title="" Language="C#" MasterPageFile="~/BenOptic.master" AutoEventWireup="true" CodeFile="ben_info.aspx.cs" Inherits="ben_info" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h1 align="center" id="ben_info_header" runat="server">
</h1>
<h3 align="center" id="ben_info_subheader" runat="server">
</h3>
<p id="ben_info_main_text" runat="server">
</p>
<form id="Form1" action='' method='post' runat='server'><asp:Button id='SaveChanges' Text='שמור' OnClick='saveChanges_Click' runat='server' /></form>
</asp:Content>
and the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class ben_info : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SaveChanges.Visible = false;
DAL data = new DAL();
if (Request.Form["submit"] != null)
{
if (Admin.LogIn(Request.Form["adm_username"], Request.Form["adm_pass"]))
{
ben_info_header.Attributes.Add("contenteditable", Session["isAdmin"].ToString());
ben_info_main_text.Attributes.Add("contenteditable", Session["isAdmin"].ToString());
ben_info_subheader.Attributes.Add("contenteditable", Session["isAdmin"].ToString());
SaveChanges.Visible = true;
SaveChanges.OnClientClick += new EventHandler(saveChanges_Click);
}
}
DataTable config = data.Select("Select * from Config where setting like 'ben_info%'");
foreach (DataRow setting in config.Rows)
{
switch (setting["setting"].ToString())
{
case "ben_info_header": ben_info_header.InnerText = setting["val"].ToString(); break;
case "ben_info_subheader": ben_info_subheader.InnerText = setting["val"].ToString(); break;
case "ben_info_main_text": ben_info_main_text.InnerText = setting["val"].ToString(); break;
}
}
}
public void saveChanges_Click(object sender, EventArgs e)
{
DAL data = new DAL();
data.Execute("update Config set val = '" + ben_info_header.InnerText + "' where setting = 'ben_info_header'");
data.Execute("update Config set val = '" + ben_info_subheader.InnerText + "' where setting = 'ben_info_subheader'");
data.Execute("update Config set val = '" + ben_info_main_text.InnerText + "' where setting = 'ben_info_main_text'");
SaveChanges.Visible = false;
}
}

To get value set in javascript in code behind

I have following in html
<div id="dvAddToGrid" runat="server">
<table style="margin-left:80%">
<tr>
<td>
<asp:LinkButton ID="lnkAddToGrid" runat="server" Text="Add New" onclick="lnkAddToGrid_Click" OnClientClick="GetValues()" Font-Underline="True"></asp:LinkButton>
</td>
</tr>
</table>
</div>
I have following in javascript
function GetValues() {
// for (i = 1; i <= 5; i++)
// {
// $("#hdnTableValues")[0].value += document.getElementById("txtSerialNo_1").value+ ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtBookName_1").value + ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtAuthor_1").value + ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtPublisher_1").value + ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtNoOfBooks_1").value + ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtRemarks_1").value + "|";
// // }
document.getElementById("lblTableValues").innerHTML = $("#hdnTableValues")[0].value ;
}
In my code behind i have
protected void lnkAddToGrid_Click(object sender, EventArgs e)
{
DataTable dtBookList = new DataTable();
dtBookList.Columns.Add("SerialNo");
dtBookList.Columns.Add("BookName");
dtBookList.Columns.Add("Author");
dtBookList.Columns.Add("Publisher");
dtBookList.Columns.Add("NoOfBooks");
dtBookList.Columns.Add("Remarks");
string str = lblTableValues.Text ;
for(int i=1;i<5;i++)
{
DataRow dtRow = dtBookList.NewRow();
//hdnTableValues.Value
}
dvBookList.Visible = false;
dvAddToGrid.Visible = false;
}
Problem is i am getting values in lblTableValues in js.But in code behid it does not contain any values its value is "".Can anybody help to get the value contained in hdnTableValues in click event in code behind.
You can use a hidden input with runat="server" to handle this. Store the value to the hidden field in JavaScript. And you can access the field value in C# code behind.
HTML
<input type="hidden" id="txtHidData" runat="server" />
JavaScript
document.getElementById ( "txtHidData" ).value = "your value";
C#
string valueInCodeBehind = txtHidData.Value;
Use the asp:HiddenField control like this: (jquery example)
in the page or control:
<asp:HiddenField ID="Hidden1" runat="server" Value="blank" />
<asp:PlaceHolder runat="server">
<script type ="text/javascript">
$(function () {
//get the id of the hidden control
var clientID = "<%= Hidden1.ClientID %>";
$("#" + clientID).val("this is from the client");
});
</script>
</asp:PlaceHolder>
In a button or submit method in code behind:
Debug.WriteLine("val: " + Hidden1.Value);

Categories