how Prevent Twice Page_Load Running - Page.IsPostBack Is always false - c#

in a strange situation my page_Load Runs twice and all of my codes are in page_Load.
i can not use Page.IsPostBac because in both of Page_Loads, it is false.
but what is strange situation ?
i have a page for download files in my project,
when you click on one of download links (i used anchors, so IsPostBack is false) page_Load runs and in page load i check DownloadPath Querystring.
if DownloadPath not be null i jump to a Handler.ashx by passing that DownloadPath for showing Download Window To My Users.
during this process i have some logs in my database and because of that twice running they will be duplicate.
but when twice running accours ?
when you try to download a link by internet download manager, page_Load runs twice!
how can i prevent second runing of page_Load or is there a way for recognize it?
EDIT :
my page_Load :
namespace NiceFileExplorer.en
{
public partial class Download : System.Web.UI.Page
{
public string Folders = "";
public string Files = "";
protected void Page_Load(object sender, EventArgs e)
{
Statistics_body_inside.DataBind();
if (Request.QueryString["Path"] != null)
{
if (Request.QueryString["Path"] == "..")
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "YouCanNotDoThatAnyMore", "YouCanNotDoThatAnyMore();", true);
}
else
{
MainCodes();
}
}
else
{
MainCodes();
}
}
private void MainCodes()
{
if (Request.QueryString["DownloadPath"] != null)
{
string DownloadPath = Request.QueryString["DownloadPath"].ToString();
string FilePath = "C:" + DownloadPath.Replace(#"/", #"\\");
if (Session["User_ID"] != null)
{
string FileName = Request.QueryString["FileName"].ToString();
string FileSize = Request.QueryString["FileSize"].ToString();
string FileCreationDate = Request.QueryString["FileCreationDate"].ToString();
int Downloaded_Count_4Today = DataLayer.Download.Count_By_UserID_Today(int.Parse(HttpContext.Current.Session["User_ID"].ToString()), DateTime.Now);
if (Downloaded_Count_4Today <= 10)
{
DataSet dsDownload = DataLayer.Download.Size_By_UserID_Today(int.Parse(HttpContext.Current.Session["User_ID"].ToString()), DateTime.Now);
if (dsDownload.Tables["Download"].Rows.Count > 0)
{
DataRow drDownload = dsDownload.Tables["Download"].Rows[0];
int SumOfFileSize4Today = int.Parse(drDownload["FileSizSum"].ToString());
if (SumOfFileSize4Today + int.Parse(FileSize) <= 1073741824)//1 GB = 1024*1024*1024 bytes = 1073741824 bytes
//if (SumOfFileSize4Today + int.Parse(FileSize) <= 100000)
{
//DataLayer.Download.InsertRow(
// int.Parse(Session["User_ID"].ToString()),
// DateTime.Now,
// FilePath.Replace(#"\\", #"\"),
// FileName,
// FileSize,
// DateTime.Parse(FileCreationDate)
// );
Response.Redirect("~/HandlerForMyFE.ashx?Downloadpath=" + HttpUtility.UrlEncode(DownloadPath));
}
else
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "YouCanNotDownloadAnyMore_SizeOverload", "YouCanNotDownloadAnyMore_SizeOverload();", true);
}
}
else
{
if (int.Parse(FileSize) <= 1073741824)
//if (int.Parse(FileSize) <= 100000)
{
//DataLayer.Download.InsertRow(
// int.Parse(Session["User_ID"].ToString()),
// DateTime.Now,
// FilePath.Replace(#"\\", #"\"),
// FileName,
// FileSize,
// DateTime.Parse(FileCreationDate)
// );
Response.Redirect("~/HandlerForMyFE.ashx?Downloadpath=" + HttpUtility.UrlEncode(DownloadPath));
}
else
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "YouCanNotDownloadAnyMore_SizeOverload", "YouCanNotDownloadAnyMore_SizeOverload();", true);
}
}
}
else
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "YouCanNotDownloadAnyMore_CountOverload", "YouCanNotDownloadAnyMore_CountOverload();", true);
}
}
else
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "plzLoginFirst_ForDownload", "plzLoginFirst_ForDownload();", true);
}
}
DirectoryInfo dir;
string lastpath = "";
try
{
lastpath = Request["path"].ToString();
}
catch { }
lblTitleInHeader.Text = "Files";
lblTitleInHeader.Text += lastpath;
//set back
string[] splited = lblTitleInHeader.Text.Split('/');
lblTitleInHeader.Text = "";
ArrayList arName = new ArrayList();
for (int i = 0; i < splited.Length; i++)
{
if (splited[i] != "")
{
arName.Add(splited[i]);
}
}
for (int i = 0; i < arName.Count - 1; i++)
{
if (i != arName.Count - 1)
{
lblTitleInHeader.Text += "<a href='Download.aspx?path=%2f";//%2f = /
for (int j = 1; j < i + 1; j++)
{
lblTitleInHeader.Text += HttpUtility.UrlEncode(arName[j].ToString() + "/");
}
lblTitleInHeader.Text += "'>" + arName[i] + "</a>" + " " + "<img class='icoSubFolder' src='../Images/Download/icoSubFolder.png' />";
}
}
lblTitleInHeader.Text += arName[arName.Count - 1].ToString();
lblTitleInHeader.Text = lblTitleInHeader.Text.Replace("/'>", "'>");
if (lastpath != "")
{
//dir = new DirectoryInfo(Server.MapPath("~/Files/" + lastpath));
dir = new DirectoryInfo(#"C:\\Files\\" + lastpath.Replace(#"/", #"\\"));
}
else
{
//dir = new DirectoryInfo(Server.MapPath("~/Files/"));
dir = new DirectoryInfo(#"C:\\Files\\");
}
int count4Folders = 0;
foreach (DirectoryInfo d in dir.GetDirectories())
{
count4Folders++;
DirectoryInfo dirSub = new DirectoryInfo(d.FullName);
int iDir = 0;
int iFile = 0;
foreach (DirectoryInfo subd in dirSub.GetDirectories())
{
iDir++;
}
foreach (FileInfo f in dirSub.GetFiles("*.*"))
{
iFile++;
}
Folders += "<div class='divFoldersBody_Row'>";
Folders += "<div class='divFoldersBody_Left'>";
Folders += " ";
Folders += "</div>";
Folders += "<div class='divFoldersBody_Name'>";
Folders += "<span class='imgFolderContainer'><img class='imgFolder' src='../Images/Download/folder.png' /></span>";
Folders += "<span class='FolderName'><a class='FolderLink' href='Download.aspx?path=" + HttpUtility.UrlEncode(lastpath + "/" + d.Name) + "'>";
Folders += d.Name;
Folders += "</a></span>";
Folders += "</div>";
Folders += "<div class='divFoldersBody_Count'>";
Folders += iDir.ToString() + " Folders & " + iFile.ToString() + " Files";
Folders += "</div>";
Folders += "<div class='divFoldersBody_Right'>";
Folders += " ";
Folders += "</div>";
Folders += "</div>";
}
if (count4Folders == 0)
{
divFoldersHeader.Style.Add("display", "none");
}
int count4Files = 0;
foreach (FileInfo f in dir.GetFiles("*.*"))
{
count4Files++;
Files += "<div class='divFilesBody_Row'>";
Files += "<div class='divFilesBody_Left'>";
Files += " ";
Files += "</div>";
Files += "<div class='divFilesBody_Name'>";
char[] Extension_ChAr = f.Extension.ToCharArray();
string Extension_str = string.Empty;
int lenghth = Extension_ChAr.Length;
for (int i = 1; i < Extension_ChAr.Length; i++)
{
Extension_str += Extension_ChAr[i];
}
if (Extension_str.ToLower() == "rar" || Extension_str.ToLower() == "zip" || Extension_str.ToLower() == "zipx" || Extension_str.ToLower() == "7z" || Extension_str.ToLower() == "cat")
{
Files += "<span class='imgFileContainer'><img class='imgFile-rar' src='../Images/Download/file-rar.png' /></span>";
}
else if (Extension_str.ToLower() == "txt" || Extension_str.ToLower() == "doc" || Extension_str.ToLower() == "docx")
{
Files += "<span class='imgFileContainer'><img class='imgFile-txt' src='../Images/Download/file-txt.png' /></span>";
}
else if (Extension_str.ToLower() == "pdf")
{
Files += "<span class='imgFileContainer'><img class='imgFile-pdf' src='../Images/Download/file-pdf.png' /></span>";
}
else if (Extension_str.ToLower() == "jpg" || (Extension_str.ToLower() == "png") || (Extension_str.ToLower() == "gif") || (Extension_str.ToLower() == "bmp") || (Extension_str.ToLower() == "psd"))
{
Files += "<span class='imgFileContainer'><img class='imgFile-image' src='../Images/Download/file-image.png' /></span>";
}
else if (Extension_str.ToLower() == "exe")
{
Files += "<span class='imgFileContainer'><img class='imgFile-exe' src='../Images/Download/file-exe.png' /></span>";
}
else
{
Files += "<span class='imgFileContainer'><img class='imgFile-unknown' src='../Images/Download/file-unknown.png' /></span>";
}
Files += "<span title='" + f.Name + "' class='FileName'>";
Files += f.Name;
Files += "</span>";
Files += "</div>";
Files += "<div class='divFilesBody_FileType'>";
Files += "<span style='color:red;'>" + Extension_str.ToUpper() + "</span>" + " File";
//Files += Path.GetExtension(f.Name) + " File";
Files += "</div>";
Files += "<div class='divFilesBody_FileSize'>";
Files += ConvertBytes.ToFileSize(long.Parse(f.Length.ToString()));
Files += "</div>";
Files += "<div class='divFilesBody_FileCreationDate'>";
Files += f.CreationTime;
Files += "</div>";
Files += "<div class='divFilesBody_FileDownload'>";
string Downloadpath = "/Files" + lastpath + "/" + f.Name;
string EncodedDownloadpath = HttpUtility.UrlEncode(Downloadpath);
Files += "<a class='FileLink' href='Download.aspx?path=" + HttpUtility.UrlEncode(lastpath) + "&Downloadpath=" + EncodedDownloadpath + "&FileName=" + HttpUtility.UrlEncode(f.Name) + "&FileSize=" + HttpUtility.UrlEncode(f.Length.ToString()) + "&FileCreationDate=" + HttpUtility.UrlEncode(f.CreationTime.ToString()) + "'>";
Files += "<img class='imgDownload' src='../Images/Download/Download.png' />";
Files += "</a>";
Files += "</div>";
Files += "<div class='divFilesBody_Right'>";
Files += " ";
Files += "</div>";
Files += "</div>";
}
if (count4Files == 0)
{
divFilesHeader.Style.Add("display", "none");
}
if ((count4Folders == 0) && (count4Files == 0))
{
divFoldersHeader.Style.Add("display", "block");
divFilesHeader.Style.Add("display", "block");
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "hash", "location.hash = '#BreadCrumbInDownload';", true);
}
....
my aspx :
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<link href="css/Download.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$('#Download-body *').css({ 'zIndex': 2 });
$('#Download-body').css({ 'overflow': 'hidden', 'position': 'relative' });
var containerWidth = $('#Download-body').innerWidth();
var containerHeight = $('#Download-body').innerHeight();
var bgimgurl = $('#Download-body').css('backgroundImage').replace(/url\(|\)|"|'/g, "");
var img = $('<img src="' + bgimgurl + '" width="' + containerWidth + 'px"' + ' height="' + containerHeight + 'px" />').css({ 'position': 'absolute', 'left': 0, 'top': 0, 'zIndex': 1 });
$('#Download-body').css({ 'background': 'transparent' }).append(img);
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="Download">
<div id="Download-header">
<div id="DownloadTitle">
Download
</div>
<asp:Image ID="imgDownload_header_left" runat="server" ImageUrl="~/Images/Download-header-left.png" />
<asp:Image ID="imgDownload_header_right" runat="server" ImageUrl="~/Images/Download-header-right.png" />
</div>
<div id="Download-body">
<div id="Download-body-inside">
<div id="Statistics">
<div id="Statistics-header">
<div id="StatisticsTitle">
Statistics
</div>
<asp:Image ID="imgStatistics_header_left" runat="server" ImageUrl="~/Images/Statistics-header-left.png" />
<asp:Image ID="imgStatistics_header_right" runat="server" ImageUrl="~/Images/Statistics-header-right.png" />
</div>
<div id="Statistics-body">
<div runat="server" id="Statistics_body_inside">
<asp:Label ID="lblDownload_Count_By_UserID_Title" runat="server" Text="Ur Download Count :"
ToolTip="Your Download Count From The Begining Of Registration UpTo Now" CssClass="lblTitleInStatistics"></asp:Label>
<asp:Label ID="lblDownload_Count_By_UserID" runat="server" Text="<%# Download_Count_By_UserID() %>"
CssClass="lblCountInStatistics"></asp:Label>
<br />
<asp:Label ID="lblDownload_Count_By_UserID_Today_Title" runat="server" Text="Ur Download Count-Today :"
ToolTip="Your Download Count-Today" CssClass="lblTitleInStatistics"></asp:Label>
<asp:Label ID="lblDownload_Count_By_UserID_Today" runat="server" Text="<%# Download_Count_By_UserID_Today() %>"
CssClass="lblCountInStatistics"></asp:Label>
<br />
<asp:Label ID="lblDownload_Size_By_UserID_Title" runat="server" Text="Ur Download Size :"
ToolTip="Your Download Size From The Begining Of Registration UpTo Now" CssClass="lblTitleInStatistics"></asp:Label>
<asp:Label ID="lblDownload_Size_By_UserID" runat="server" Text="<%# Download_Size_By_UserID() %>"
CssClass="lblCountInStatistics"></asp:Label>
<br />
<asp:Label ID="lblDownload_Size_By_UserID_Today_Title" runat="server" Text="Ur Download Size-Today :"
ToolTip="Your Download Size-Today" CssClass="lblTitleInStatistics"></asp:Label>
<asp:Label ID="lblDownload_Size_By_UserID_Today" runat="server" Text="<%# Download_Size_By_UserID_Today() %>"
CssClass="lblCountInStatistics"></asp:Label>
<br />
<asp:Label ID="lblDownload_Size_By_UserID_Today_Remain_Title" runat="server" Text="Ur Remain Download Size-Today :"
ToolTip="Your Remain Download Size-Today" CssClass="lblTitleInStatistics"></asp:Label>
<asp:Label ID="lblDownload_Size_By_UserID_Today_Remain" runat="server" Text="<%# Download_Size_By_UserID_Today_Remain() %>"
CssClass="lblCountInStatistics"></asp:Label>
</div>
</div>
</div>
<div id="MainDivInDownload">
<div id="BreadCrumbInDownload">
<div id="imgicoHomeContainer">
<asp:Image ID="imgicoHome" runat="server" ImageUrl="~/Images/Download/icoHome.png" />
</div>
<div id="lblTitleInHeaderContainer">
<asp:Label ID="lblTitleInHeader" runat="server" Text=""></asp:Label>
</div>
<div style="clear: both;">
</div>
</div>
<div runat="server" id="divFolders">
<div runat="server" id="divFoldersHeader">
<div id="divFoldersHeader_Left">
<asp:Image ID="divFoldersHeader_imgLeft" runat="server" ImageUrl="~/Images/Download/divsHeader_Left.png" />
</div>
<div id="divFoldersHeader_Name">
Folders In This Folder
</div>
<div id="divFoldersHeader_Count">
Total Files In This Folder
</div>
<div id="divFoldersHeader_Right">
<asp:Image ID="divFoldersHeader_imgRight" runat="server" ImageUrl="~/Images/Download/divsHeader_Right.png" />
</div>
</div>
<div id="divFoldersBody">
<%-- <div class="divFoldersBody_Row">
<div class="divFoldersBody_Left">
</div>
<div class="divFoldersBody_Name">
<span class="imgFolderContainer">
<asp:Image CssClass="imgFolder" runat="server" ImageUrl="~/Images/Download/folder.png" />
</span><span class="FolderName"><a class="FolderLink" href="#">Folders In This Folder</a></span>
</div>
<div class="divFoldersBody_Count">
Total Files In This Folder
</div>
<div class="divFoldersBody_Right">
</div>
</div>--%>
<%= Folders %>
</div>
</div>
<div runat="server" id="divFiles">
<div runat="server" id="divFilesHeader">
<div id="divFilesHeader_Left">
<asp:Image ID="divFilesHeader_imgLeft" runat="server" ImageUrl="~/Images/Download/divsHeader_Left.png" />
</div>
<div id="divFilesHeader_Name">
Files In This Folder
</div>
<div id="divFilesHeader_FileType">
File Type
</div>
<div id="divFilesHeader_FileSize">
File Size
</div>
<div id="divFilesHeader_FileCreationDate">
File Creation Date
</div>
<div id="divFilesHeader_FileDownload">
</div>
<div id="divFilesHeader_Right">
<asp:Image ID="divFilesHeader_imgRight" runat="server" ImageUrl="~/Images/Download/divsHeader_Right.png" />
</div>
</div>
<div id="divFilesBody">
<%-- <div class="divFilesBody_Row">
<div class="divFilesBody_Left">
</div>
<div class="divFilesBody_Name">
<span class="imgFileContainer">
<asp:Image runat="server" ImageUrl="~/Images/Download/file.png" CssClass="imgFile" />
</span><span class="FileName">Files In This Folder</span>
</div>
<div class="divFilesBody_FileType">
File Type
</div>
<div class="divFilesBody_FileSize">
File Size
</div>
<div class="divFilesBody_FileCreationDate">
File Creation Date
</div>
<div class="divFilesBody_FileDownload">
<a class="FileLink" href="#">
<asp:Image CssClass="imgDownload" runat="server" ImageUrl="~/Images/Download.png" />
</a>
</div>
<div class="divFilesBody_Right">
</div>
</div>--%>
<%= Files %>
</div>
</div>
</div>
</div>
</div>
</div>
</asp:Content>
thanks in advance

Please look at the html as it is rendered on the page:
Every time it's present
<img src=""/>
double postback can happen, for some browser...
If this is the trouble, you can resolve it setting a default, blank, image for every button
<asp:ImageButton ImageUrl="~/Images/blank.gif"...

Related

How to update multiple div contents using C#?

In a Get Response from an API, I need to update the div's accordingly.
Below is my HTML Code
<div class="col-md-2 mb-4">
<div class="card mb-4" id="roomName_1" runat="server">
<div class="card-header text-center">
Room 1
</div>
<div class="card-body" style="background-color:#ff0000;color:white;">
<p>
<asp:Literal Text="Organizer" runat="server" ID="organiser_1" />
<br />
<label id="from_1">From</label>
-
<label id="to_1">To</label>
<br />
<asp:Literal Text="Subject" runat="server" ID="subject_1" />
</p>
</div>
</div>
</div>
There are 24 rooms like this, and for each room I have to update Organizer, From, To, Subject which I get from a GET Request.
private void GetRoom(string uri) {
var request = WebRequest.Create(uri);
string text;
var response = (HttpWebResponse)request.GetResponse();
request.ContentType = "application/json; charset=utf-8";
using(var sr = new StreamReader(response.GetResponseStream())) {
text = sr.ReadToEnd();
List<RoomConfigurationViewInfo> roomObject = JsonConvert.DeserializeObject < List<RoomConfigurationViewInfo>> (text);
foreach(var value in roomObject) {
Response.Write(value.Organizer);
Response.Write(value.Subject);
}
}
}
So, Is it possible to Update multiple Div's using C#? & if not then how can I achieve this.
Please suggest.
I found a way that you can achieve this:
At first, add ID to your first tag: <div id="rooms" runat="server" class="col-md-2 mb-4">
Now in code behind, you can try this:
private void GetRoom(string uri)
{
var request = WebRequest.Create(uri);
string text;
var response = (HttpWebResponse)request.GetResponse();
request.ContentType = "application/json; charset=utf-8";
using(var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
List<RoomConfigurationViewInfo> roomObject = JsonConvert.DeserializeObject < List<RoomConfigurationViewInfo>> (text);
rooms.InnerHtml = "";
for(int i = 0; i < roomObject.Count; i++)
{
string strOrganizer = roomObject[i].Organizer;
string strSubject = roomObject[i].Subject;
string strFrom = roomObject[i].From;
string strTo = roomObject[i].To;
rooms.InnerHtml += "<div class=\"card mb-4\">"
+ "<div class=\"card-header text-center\">"
+ "Room " + i + "";
+ "</div>"
+ "<div class=\"card-body\" style=\"background-color:#ff0000;color:white;\">"
+ "<p>"
+ "<asp:Literal Text=\"" + strOrganizer "\" runat=\"server\" ID=\"organiser_" + i + "\"/>"
+ "<br />"
+ "<label>" + strFrom + "</label>"
+ "-"
+ "<label>" + strTo + "</label>"
+ "<br />"
+ "<asp:Literal Text=\"" + strSubject + "\" runat=\"server\" ID=\"subject_" + i + "\" />"
+ "</p>"
+ "</div>"
+ "</div>";
}
}
}
I hope it helps you
It depends if you are doing it dynamically or not. If you are simply loading the page and updating the divs, pass it as a variable and then iterate through it.
Your code on your page would be something like this:
<% foreach (var myItem in g) { %>
<p>
<%= myItem.Organizer%>
<br />
<label id="from_1">From</label>
-
<label id="to_1">To</label>
<br />
<%= myItem.Subject%>
</p>
<% } %>
If you are trying to do it dynamically, the commenter above is correct and you would have to do it through jQuery/Javascript.

Use Hyperlink in code

how can i use a asp:hyperlink in my code where the user can press the number and go to another page, so this is my code,
if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
loggedin.Text = "Registered users today: " + dr["RegisteredUsersToday"];
}
if (dtParent != null)
{
foreach (DataRow dr in dtParent.Rows)
{
loggedinParents.Text = "Registered Parents today: " + dr["RegisteredUsersToday"];
}
}
else
{
loggedinParents.Text = "Registered Parents today: 0 ";
}
if (dtTeacher != null)
{
foreach (DataRow dr in dtTeacher.Rows)
{
loggedinTeachers.Text = "Registered Teachers today: " + dr["RegisteredUsersToday"];
}
}
else
{
loggedinTeachers.Text = "Registered Teachers today: 0 ";
}
if (dtStudents != null)
{
foreach (DataRow dr in dtStudents.Rows)
{
loggedinStudents.Text = "Registered Students today: " + dr["RegisteredUsersToday"];
}
}
else
{
loggedinStudents.Text = "Registered Students today: 0 ";
}
}
else
{
loggedin.Text = "No new users today";
}
i want the hyperlink to be between RegisteredUsersToday, and this is my html where a have created the labels,
<div class="panel panel-default">
<div class="text-center panel-heading">
<a data-toggle="collapse" href="#collapse1" >
<asp:Label runat="server" ID="loggedin"></asp:Label>
</a>
</div>
<br />
<div id="collapse1" class="panel-collapse collapse">
<div class="text-center">
<asp:Label runat="server" ID="loggedinParents"></asp:Label>
</div>
<br />
<div class="text-center">
<asp:Label runat="server" ID="loggedinTeachers"></asp:Label>
</div>
<br />
<div class="text-center">
<asp:Label runat="server" ID="loggedinStudents"></asp:Label>
</div>
</div>
</div>

ASP.NET check which button was clicked

Here's the deal, I making a website that sells some products and according to how much products I have the ammount of buttons changes too.
For example if I have 5 products I will have 5 buttons, something like this:
What I want to do is when a button is clicked I want to take the item name and save it (in a session) so I can use this information on a different page (the code behind is in C#).
How can I do this?
Html:
<div runat="server" id="CatalogProducts" class="container-fluid">
</div>
Code behind:
SqlHey SQLViewProducts = new SqlHey();
DataSet DSViewProducts = new DataSet();
string Sheilta = "SELECT TblShop.ItemName, TblShop.Price, TblShop.ShopType, TblShop.Image, TblShop.Description FROM TblShop;";
DSViewProducts = SQLViewProducts.chkData(Sheilta);
int I;
for (I = 0; I < DSViewProducts.Tables[0].Rows.Count; I++)
{
if (DSViewProducts.Tables[0].Rows.Count % 2 == 0)
{
if (I % 2 == 0)
CatalogProducts.InnerHtml += " <div class=\"row\"> <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף<span style=\"font-size: 0.65em\"></span> <asp:Button ID=\"Button1\" runat=\"server\" BackColor=\"Transparent\" BorderStyle=\"None\" ForeColor=\"Transparent\" Height=\"43px\" Style=Height=\"z-index: 99; left: 0px; position: absolute; top: 0px\" Text=\"a\" Width=\"87px\" />לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div>";
else CatalogProducts.InnerHtml += " <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף<span style=\"font-size: 0.65em\"></span> <asp:Button ID=\"Button1\" runat=\"server\" BackColor=\"Transparent\" BorderStyle=\"None\" ForeColor=\"Transparent\" Height=\"43px\" Style=Height=\"z-index: 99; left: 0px; position: absolute; top: 0px\" Text=\"a\" Width=\"87px\" />לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div> </div> <br /> <br />";
}
if (DSViewProducts.Tables[0].Rows.Count % 2 != 0)
{
if (I + 1 == DSViewProducts.Tables[0].Rows.Count)
CatalogProducts.InnerHtml += " <div class=\"row\"> <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div>";
if (I % 2 == 0)
CatalogProducts.InnerHtml += " <div class=\"row\"> <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף<span style=\"font-size: 0.65em\"></span> <asp:Button ID=\"Button1\" runat=\"server\" BackColor=\"Transparent\" BorderStyle=\"None\" ForeColor=\"Transparent\" Height=\"43px\" Style=Height=\"z-index: 99; left: 0px; position: absolute; top: 0px\" Text=\"a\" Width=\"87px\" />לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div> </div> <br /> <br />";
else CatalogProducts.InnerHtml += " <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף<span style=\"font-size: 0.65em\"></span> <asp:Button ID=\"Button1\" runat=\"server\" BackColor=\"Transparent\" BorderStyle=\"None\" ForeColor=\"Transparent\" Height=\"43px\" Style=Height=\"z-index: 99; left: 0px; position: absolute; top: 0px\" Text=\"a\" Width=\"87px\" />לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div> </div> <br /> <br />";
}
}
The methood chkData:
public DataSet chkData(string sqlstr)
{
string path = HttpContext.Current.Server.MapPath("~/App_Data/");
string fileName = "Hey.mdb";
path += fileName;
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + path;
OleDbConnection conn = new OleDbConnection(connString);
OleDbDataAdapter da = new OleDbDataAdapter(sqlstr, conn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
In the CatalogProducts.InnerHtml bind the for loop count to button ID,if not possible to bind then try instead of asp button you may use input type="button"
I just added to your code refer this..
<input type="Button" id=\"Button_\"+I />
It's better to use Repeater for this solution. Check out this link. It will tell you what to do step by step.

feature list out and throw it into the foreach

My requirement is that I must have everything in my list display on the page.
The problem is that, with the code I have, it only displays one thing no matter what it is !
Therefore, I would like to know what is going wrong since it does not show more than a thing forward?
default.aspx.cs
DataClassesDataContext db = new DataClassesDataContext();
List<ForslagOpslag> forslagopslag = db.ForslagOpslags.ToList();
foreach (ForslagOpslag item in forslagopslag)
{
//udskriver tekst på siden.
LabelText.Text = item.text;
}
Default.aspx
<asp:Label ID="LabelText" runat="server"></asp:Label>
It displays only one FORWARD, it does not display the rest.
EIDT:
Default.aspx / html
<asp:Label ID="LabelBrugernavn" runat="server"></asp:Label>
<asp:Literal ID="LiteralLikesOpslag" runat="server"></asp:Literal>
<asp:Literal ID="LiteralDelete" runat="server"></asp:Literal>
<div style="margin-bottom: 5px; clear: both;"></div>
<asp:Label ID="LabelText" runat="server"></asp:Label>
<div style="margin-top: 5px; clear: both;"></div>
<div class="col-md-12">
<hr class="tall" style="margin:7px 0;">
</div>
Default.aspx.cs
List<ForslagOpslag> forslagopslag = db.ForslagOpslags.ToList();
foreach (ForslagOpslag item in forslagopslag)
{
//find ud af likes til forslaget.
var likesFjern = db.ForslagOpslagLikes.Where(a => a.fk_brugerid == Helper.ReturnBrugerId()).Count();
//udskriver fornavn og efternavn
LabelBrugernavn.Text = item.brugere.fornavn + " " + item.brugere.efternavn;
//udskriver tekst på siden.
LabelText.Text = item.text;
//finder ud af om man har synes godt om forslag før.
if (likesFjern >= 1)
{
LiteralLikesOpslag.Text = "<a href='fjernsynesgodtom.aspx?id=" + item.Id + "&brugerid=" + Helper.ReturnBrugerId() + "' class='btn btn-danger btn-xs'>Fjern synes godt om</a>";
}
else if (item.brugere.Id != Helper.ReturnBrugerId())
{
LiteralLikesOpslag.Text = "<a href='SynesGodtOm.aspx?id=" + item.Id + "' class='btn btn-success btn-xs'>Like opslag - " + item.ForslagOpslagLikes.Count() + " synes godt om</a>";
}
else
{
LiteralLikesOpslag.Text = "<p class='label label-lg label-success'>" + item.ForslagOpslagLikes.Count() + " synes godt om</p>";
}
//slet opslag både admin og brugeren selv.
//giver det muligt for admin at kunne slette opslag.
if ((item.fk_brugerid == Helper.ReturnBrugerId() || Helper.BrugerRank(Helper.ReturnBrugerId()) == 1))
{
LiteralDelete.Text = "<a href='slet.aspx?id=" + item.Id + "' class='btn btn-danger btn-xs'>Slet</a>";
}
}
You are always resetting the text of the label so effectively, only the last item is shown.
If you want to display all the items, you need to concatinate them.
foreach (ForslagOpslag item in forslagopslag)
{
//udskriver tekst på siden.
LabelText.Text += item.text;
}
Notice the plus sign, to concatinate the strings.
UPDATE, to render an unordered list:
string list = "<ul>";
foreach (ForslagOpslag item in forslagopslag)
{
//udskriver tekst på siden.
list += "<li>" + item.text + "</li>";
}
list += "</ul>";
placeholder.Controls.Add(new LiteralControl(list));
Then change your .aspx page and remove the label and add this instead:
<asp:PlaceHolder runat="server" ID="placeholder" />
You are resetting the text with each new item, use a StringBuilder to create a the longer string, or an itemrepeater so that you can display more than one item at once
So, with a StringBuilder, you could do it as such:
StringBuilder allText = new StringBuilder();
foreach (ForslagOpslag item in forslagopslag) {
allText.AppendLine(item.text);
}
LabelText.Text = allText.ToString();
or you could use another control like an Repeater to display the full dataset at once, with a template, for example as such:
<asp:Repeater ID="itemRepeater" runat="server">
<ItemTemplate>
<div><asp:Label ID="lblTest" runat="server" Text='<%#Bind("text")%>' /></div>
</ItemTemplate>
</asp:Repeater>
and in your code behind, you could add it to the page load event, as such:
itemRepeater.DataSource = forslagopslag;
itemRepeater.DataBind();
This also allows you to bind to multiple elements, or to define a header template or, just look into the Repeater MSDN help page

Garden label into Repeater to find my label

It is such that I have a Repeater with both label and Literal content, and that is how I got it into Repeater and I would like it being like shown at the side.
It appears with the error that tells me that it can not find my label or Literal
Repeater her:
<asp:Repeater ID="RepeaterOpslag" runat="server">
<ItemTemplate>
<div id="forslagbox" runat="server">
<asp:Label ID="LabelBrugernavn" runat="server"></asp:Label>
<asp:Literal ID="LiteralLikesOpslag" runat="server"></asp:Literal>
<asp:Literal ID="LiteralDelete" runat="server"></asp:Literal>
<div style="margin-bottom: 5px; clear: both;"></div>
<asp:Label ID="LabelText" runat="server"></asp:Label>
<div style="margin-top: 5px; clear: both;"></div>
<div class="col-md-12">
<hr class="tall" style="margin: 7px 0;">
</div>
</div>
</ItemTemplate>
</asp:Repeater>
Default.aspx.cs here, It is in foreach which gives me problems that it will not print any of it at all.
RepeaterOpslag.DataSource = db.ForslagOpslags.ToList();
RepeaterOpslag.DataBind();
List<ForslagOpslag> forslagopslag = db.ForslagOpslags.ToList();
foreach (ForslagOpslag item in forslagopslag)
{
var likesFjern = db.ForslagOpslagLikes.Where(a => a.fk_brugerid == Helper.ReturnBrugerId()).Count();
LabelBrugernavn.Text = item.brugere.fornavn + " " + item.brugere.efternavn;
LabelText.Text = item.text;
if (likesFjern >= 1)
{
LiteralLikesOpslag.Text = "<a href='fjernsynesgodtom.aspx?id=" + item.Id + "&brugerid=" + Helper.ReturnBrugerId() + "' class='btn btn-danger btn-xs'>Fjern synes godt om</a>";
}
else if (item.brugere.Id != Helper.ReturnBrugerId())
{
LiteralLikesOpslag.Text = "<a href='SynesGodtOm.aspx?id=" + item.Id + "' class='btn btn-success btn-xs'>Like opslag - " + item.ForslagOpslagLikes.Count() + " synes godt om</a>";
}
else
{
LiteralLikesOpslag.Text = "<p class='label label-lg label-success'>" + item.ForslagOpslagLikes.Count() + " synes godt om</p>";
}
if ((item.fk_brugerid == Helper.ReturnBrugerId() || Helper.BrugerRank(Helper.ReturnBrugerId()) == 1))
{
LiteralDelete.Text = "<a href='slet.aspx?id=" + item.Id + "' class='btn btn-danger btn-xs'>Slet</a>";
}
}

Categories