Update panel doesn't work in asp.net - c#

I am trying to show online train in my page without any refresh. So I think I have to use updatepanel. My panel should be updated every second.
Let explain my code.
I put this part of code in my page:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="UpdatePanel1_Load">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
So I put an interval function to refresh my panel like this,
<script type="text/javascript">
$(function () {
setInterval("__doPostBack('<%=UpdatePanel1.ClientID%>', '');", 1000);
});
In my code behind I put all fetched data,
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
foreach (var t in OnlineTrainList)
{
Response.Write("<div id='train-box' style='margin-left:" + (t.XTrainLocation - 8) + "px;margin-top:" + t.YTrainLocation + "px;background:" + t.Train.TrainColor + "'>" +
"<span>" +
t.TrainId +
"</span>" +
"</div>");
List<Sensor> PassedSensor = new List<Sensor>();
PassedSensor = SensorRepository.FindBy(i => i.CurrentTrainId == t.TrainId).ToList();
string color = TrainRepository.FindBy(i => i.Id == t.TrainId).First().TrainColor;
foreach (Sensor sensor in PassedSensor)
{
Response.Write("<div class='CurrentColor-Sensor' style='margin-left:" + (sensor.XLocation - 1) + "px;margin-top:" + (sensor.YLocation + 8) + "px;background:" + color + "'></div>");
}
}
}
So my problem is the panel doesn't refresh .And my panel UpdatePanel1_Load just call one time.

So your code is:
foreach (var t in OnlineTrainList)
{
Response.Write("<div id='train-box' style='margin-left:" + (t.XTrainLocation - 8) + "px;margin-top:" + t.YTrainLocation + "px;background:" + t.Train.TrainColor + "'>" +
"<span>" +
t.TrainId +
"</span>" +
"</div>");
List<Sensor> PassedSensor = new List<Sensor>();
PassedSensor = SensorRepository.FindBy(i => i.CurrentTrainId == t.TrainId).ToList();
string color = TrainRepository.FindBy(i => i.Id == t.TrainId).First().TrainColor;
foreach (Sensor sensor in PassedSensor)
{
Response.Write("<div class='CurrentColor-Sensor' style='margin-left:" + (sensor.XLocation - 1) + "px;margin-top:" + (sensor.YLocation + 8) + "px;background:" + color + "'></div>");
}
}
first thing i must bring your attention to the id that you assign to all those divs, it must be unique and never the same. you could use an increment variable and append it to your div's id eg: div0, div1... etc
now lets have a look at the first row inside the loop. what it basically has, is a <span> nested inside a <div> and containing some attributes with text.
the Asp.Net way of handling elements would be object oriented instead of just html string:
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
//clear the update panel
UpdatePanel1.ContentTemplateContainer.Controls.Clear();
//var to generate unique div id's
int divIDIncrement = 0;
foreach (var t in OnlineTrainList)
{
//increment the id generator
divIDIncrement++;
// create a a DIV element
HtmlGenericControl _tempDIV = new HtmlGenericControl("div");
//set the attributes for the div
_tempDIV.ID = "train-box" + divIDIncrement.ToString();
_tempDIV.Style["margin-left"] = (t.XTrainLocation - 8).ToString() + "px";
_tempDIV.Style["margin-top"] = t.YTrainLocation.ToString() + "px";
_tempDIV.Style["background"] = t.Train.TrainColor.ToString();
//create the inner span
HtmlGenericControl _tempSPAN = new HtmlGenericControl("span");
//set the span's innerText
_tempSPAN.InnerText = t.TrainId.ToString();
//add the span into the Div
_tempDIV.Controls.Add(_tempSPAN);
//add the Div into your UpdatePanel
UpdatePanel1.ContentTemplateContainer.Controls.Add(_tempDIV);
List<Sensor> PassedSensor = new List<Sensor>();
PassedSensor = SensorRepository.FindBy(i => i.CurrentTrainId == t.TrainId).ToList();
string color = TrainRepository.FindBy(i => i.Id == t.TrainId).First().TrainColor;
foreach (Sensor sensor in PassedSensor)
{
// create another div for the sub stuff
HtmlGenericControl _tempSubDIV = new HtmlGenericControl("div");
_tempSubDIV.Attributes["class"] = "CurrentColor-Sensor";
_tempSubDIV.Style["margin-left"] = (sensor.XLocation - 1).ToString() + "px";
_tempSubDIV.Style["margin-top"] = (sensor.YLocation + 8).ToString() + "px";
_tempSubDIV.Style["background"] = color.ToString();
//add the sub stuff to the update panel
UpdatePanel1.ContentTemplateContainer.Controls.Add(_tempSubDIV);
}
}
}

Related

How to add trigger dynamically to controls that are created dynamically

I have created a bunch of html element programatically in asp.net webforms and I have an UpdatePanel on my aspx page. Now I want to add triggers for every element's click event that are created.
Here is my code
string content = "";
int i = 1000;
string btnRight = "";
string btnLeft = "";
GroupsRepository gr = new GroupsRepository();
List<Group> groups = new List<Group>();
groups = gr.LoadListAllGroups();
foreach (Group gp in groups)
{
btnLeft = "<button class='btnLeftService' runat='server' value='مقالات' />";
btnRight = "<button class='btnRightService' id='" + gp.GroupID.ToString() + "' runat='server' onserverclick='subGroups_ServerClick' value='زیر گروه ها' />";
content += "<div class='item'>";
content += "<div class='row m0 service '><div class='row m0 innerRow item'><div><i class='fa fa-laptop'></i><div class='serviceName'>" + gp.Title + "</div></div><div class='item-overlay left'><ul><li class='liLeft'>" + btnLeft + "</li><li class='liRight'>" + btnRight + "</li></ul></div></div></div>";
i++;
}
ourServises.InnerHtml = content;
GroupsRepository gr = new GroupsRepository();
List<Group> groups = new List<Group>();
groups = gr.LoadListAllGroups();
foreach (Group gp in groups)
{
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
trigger.ControlID = gp.GroupID.ToString();
trigger.EventName = "Click";
updatepanel2.Triggers.Add(trigger);
}
but at runtime, I get this error:
A control with ID '1' could not be found for the trigger in UpdatePanel 'updatepanel2'.
What should I do?

Calculate duration of the memory game and send it to the database

I need to calculate a total duration of the memory game. At the moment I can count the clicks, but I need to figure out how long it takes to open all images in sec. How can I send it to the database? I've tried some code but with no luck. This is my first experience with JavaScript, so please forgive me if the answer is obvious. Thanks for any advice.
Update: #Pieter21 Unfortunately it didn't work. I got an error: String was not recognized as a valid DateTime. At the moment "Duration" is a Timestamp in my localDB.
Javascript :
<script>
var BoxOpened = "";
var ImageOpened = "";
var startTime = new Date().getTime();
var Counter = 0;
var ImageFound = 0;
var Source = "#memorybox";
var ImageSource = [
"Images/animals/cow.jpg",
"Images/animals/cow2.jpg",
"Images/animals/sheep.jpg",
"Images/food/lemon.jpg",
"Images/animals/elephant.jpg",
"Images/animals/giraffe.jpg",
"Images/food/banana.jpg",
"Images/animals/dog.jpg",
"Images/animals/horse.jpg",
"Images/animals/lion.jpg"
];
function RandomFunction(MaxValue, MinValue) {
return Math.round(Math.random() * (MaxValue - MinValue) + MinValue);
}
function ShuffleImages() {
var ImageAll = $(Source).children();
var ImageThis = $(Source + " div:first-child");
var ImageArr = new Array();
for (var i = 0; i < ImageAll.length; i++) {
ImageArr[i] = $("#" + ImageThis.attr("id") + " img").attr("src");
ImageThis = ImageThis.next();
}
ImageThis = $(Source + " div:first-child");
for (var z = 0; z < ImgageAll.length; z++) {
var RandomNumber = RandomFunction(0, ImgArr.length - 1);
$("#" + ImageThis.attr("id") + " img").attr("src", ImageArr[RandomNumber]);
ImageArr.splice(RandomNumber, 1);
ImageThis = ImageThis.next();
}
}
function ResetGame() {
ShuffleImages();
$(Source + " div img").hide();
$(Source + " div").css("visibility", "visible");
Counter = 0;
$("#success").remove();
$("#counter").html("" + Counter);
BoxOpened = "";
ImageOpened = "";
ImageFound = 0;
return false;
}
function OpenCard() {
var id = $(this).attr("id");
if ($("#" + id + " img").is(":hidden")) {
$(Source + " div").unbind("click", OpenCard);
$("#" + id + " img").slideDown('fast');
if (ImageOpened == "") {
BoxOpened = id;
ImageOpened = $("#" + id + " img").attr("src");
setTimeout(function () {
$(Source + " div").bind("click", OpenCard)
}, 300);
} else {
CurrentOpened = $("#" + id + " img").attr("src");
if (ImageOpened != CurrentOpened) {
setTimeout(function () {
$("#" + id + " img").slideUp('fast');
$("#" + BoxOpened + " img").slideUp('fast');
BoxOpened = "";
ImageOpened = "";
}, 400);
} else {
$("#" + id + " img").parent().css("visibility", "hidden");
$("#" + BoxOpened + " img").parent().css("visibility", "hidden");
ImageFound++;
BoxOpened = "";
ImageOpened = "";
}
setTimeout(function () {
$(Source + " div").bind("click", OpenCard)
}, 400);
}
Counter++;
$("#<%=HiddenField1.ClientID%>").val(Counter);
$("#counter").html("" + Counter);
if (ImageFound == ImageSource.length) {
$("#counter").prepend('<span id="success" runat="server">You Found All Pictues With </span>');
setTimeout(function () {
var endTime = new Date().getTime();
console.log("duration = " + (endTime - startTime));
}, 1500);
//$("#HiddenField2").html("" + (endTime - startTime));
//alert(endTime - startTime);
$("#<%=HiddenField2.ClientID%>").val(endTime - startTime);
}
}
}
$(function () {
for (var y = 1; y < 3 ; y++) {
$.each(ImageSource, function (i, val) {
$(Source).append("<div id=card" + y + i + "><img src=" + val + " />");
});
}
$(Source + " div").click(OpenCard);
ShuffleImages();
});
HTML :
<span id="Span1" class="button" runat="server">
<span id="counter" >0 </span>
Clicks </span>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:HiddenField ID="HiddenField2" runat="server" />
<span class="button">
<a onclick="ResetGame();">Reset</a>
</span>
<asp:Button ID="Save" runat="server" Text="Save" OnClick="Button1_Click" CssClass="button" />
C# :
SqlConnection connection = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int value = int.Parse(HiddenField1.Value);
DateTime time = Convert.ToDateTime(HiddenField2.Value);
connection = DatabaseConnectionSetup();
SqlCommand submitCommand;
try
{
submitCommand = new SqlCommand("ResultInsert", connection);
submitCommand.CommandType = CommandType.StoredProcedure;
submitCommand.Parameters.AddWithValue("#Duration", HiddenField2.Value);
submitCommand.Parameters.AddWithValue("#UserScore", HiddenField1.Value);
connection.Open();
submitCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
}
finally
{
connection.Close();
}
}
private SqlConnection DatabaseConnectionSetup()
{
try
{
ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["MonkeyClubConnectionString"];
if (connectionString != null)
{
connection = new SqlConnection(connectionString.ConnectionString);
}
}
catch (Exception ex)
{
}
return connection;
}
You are doing the game length calculations only on the client side.
I think you already show some intentions to store it in a "hidden field 2", but you don't follow through. Uncomment the field in ASP.NET, fill it with Javascipt in the javascript, and copy it in the C# codebehind.
You also have to make sure that what you store in the field can be recognized as a datetime in SQL.

How to remove undefined array in asp.net?

I am trying to select folder content
In that folder contain images when I am select that folder it will select all content.
plus it is taking img src undefind
so I need to remove that how can I remove if src is undefined using asp.net c#
<div id="cell" class="box2">
<a href="undefined">
<img width="260px" height="135px" src="undefined"
alt=""
style="box-shadow: 1px 2px 2px #BDBDBD;
border: 1px solid #D1D1D1;">
</img>
</a>
</div>
Code behind file:
protected void chbindustry_SelectedIndexChanged(object sender, EventArgs e)
{
if (result == false)
{
string[] subdirectoryEntries = Directory.GetDirectories(Server.MapPath("BusinessCards"));
string f;
string[] ss;
string side = chklist.SelectedValue;// RadioButtonList1.SelectedValue;
foreach (ListItem li in chbindustry.Items)
{
if (li.Selected)
{
ss = li.Text.Split('(');
f = Server.MapPath("BusinessCards").ToString() + "\\" + ss[0];
int c = f.Count();
DirectoryInfo d = new DirectoryInfo(f);
int len = d.GetFiles().Length;
for (int i = 1; i <= d.GetFiles().Length / 3; i++)
{
Page.ClientScript.RegisterArrayDeclaration("ImgPaths", "'" + "BusinessCards/" + f.Remove(0, f.LastIndexOf('\\') + 1) + "/" + i + ".jpg'");
Page.ClientScript.RegisterArrayDeclaration("refs", "'" + "DesignBCs.aspx?img=BusinessCards/" + f.Remove(0, f.LastIndexOf('\\') + 1) + "/" + i + "&Side=" + side + "'");
}
}
}
}
result = true;
}
Assuming you have a list of the image src values in C#, you could use LINQ to filter out any of them that are undefined:
var list = some code to get a list of img srcs from your folder;
list = list.Where(value => !string.IsNullOrWhitespace(value)).ToList();
The lambda value => !string.IsNullOrWhitespace(value) filters list such that each element is not null or whitespace (what I'm assuming you mean by undefined).
Does this help? If you can share some sample code of what you have now we can help more.

ASP.NET How to use Counter with '<%=

I want to make a multiple upload, iam using some script from this forum.
the scripts is perfectly works, but when i merge it with my project.
javascript can't get the value of my element.
i found out the problem is because i have many ID PANEL in the page, i need to change to getElementByID('<%="FileUpdate.ClientID%>').value (the original : getElementByID("FileUpdate").value)
THE PROBLEM IS :
I have to use counter, ex: getElementByID('<%="txtFileUpdate' + counter + '%>').value but it FAIL.
the error says "too many characters in character literal" pointing to that line.
Please someone help, is there any solution for this problem ?
Here is the script
-----> Error " to many characters in character literal"
<script type="text/javascript" language="javascript">
var counter = 1;
function AddFileUpload() {
if (counter < 5) {
counter++;
var div = document.createElement('DIV');
div.innerHTML = '<input id="FileUpload' + counter + '" name = "file' + counter +
'" type="file" />' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainers").appendChild(div);
}
else {
alert("Cannot attach more than 5 file");
}
}
function GetFile() {
var temp;
var error = "";
var stringx = "";
var exCounter = 1 ;
for (exCounter; exCounter <= counter; exCounter++) {
-----> stringx = document.getElementById('<%=FileUpload'+exCounter+'.ClientID%>').value;
if (stringx != "")
temp += stringx + "#;";
else
error += exCounter + ", ";
}
if (error != "") {
alert("Field " + error + " Still Empty");
return;
}
document.getElementById('<%=HiddenField1.ClientID%>').value = temp;
}
Try this:
getElementByID('FileUpdate<%=counter%>').value
or
getElementByID('<%=txtFileUpdate + counter.ToString()%>').value

Implement a HierarchicalDataBoundControl for ASP.NET

I want to implement a Hierarchical data bound control for ASP.NET.
I used Implementing IHierarchy Support Into Your Custom Collection as a basis to create my hierarchical collection. I also created a HierarchicalDataSourceControl for the collection. Everything works: I can bind it to an ASP.NET TreeView and it renders the data correctly.
However, I'm stuck on the HierarchicalDataBoundControl. I found examples, but I am still too new at c# / .Net to understand them. I don't quite understand how to implement the examples:
Rendering a databound UL menu
nor
HierarchicalDataBoundControl Class
Does anyone have any tips, or better examples of implementing a control like this?
As another DataBound controls you have to override PerformDataBinding method as follows.
protected override void PerformDataBinding()
{
base.PerformDataBinding();
if (!IsBoundUsingDataSourceID && this.DataSource == null) return;
HierarchicalDataSourceView view = this.GetData(string.Empty);
if (view != null)
{
IHierarchicalEnumerable root = view.Select();
}
}
Whereas your control supports DataSource and HierarchialDataSource control in this case, should check if there is an assigned DataSource, get its DataSourceView to accomplish data binding. It's practicable through GetData method. Then call view's Select method to get the root collection.
Afterwards, you have to iterate through root collection that is an object of type IHierarchialEnumerable. It has a simple method called GetHierarchyData that gives an object which is an item of the collection and returns an associated IHierarchyData that describes a node. This methods is there, therefore in most times you don't know the actual type of item. IHierarchyData represents some information about a node and its children.
Lastly, you don't need to write a new DataSource control. If you are after creating a custom navigation control, it's better to write a new provider for SiteMapDataSource.
I faced similar problem and created my own raw html.
private void LoadCategory()
{
String s = "";
// Prepare your dataset DataSet ds
// Note That I have Category Table having C_NAME AND PC_NAME coloums, change it as per your column anme
ds.Relations.Add("rsParentChild", ds.Tables[0].Columns["C_NAME"], ds.Tables[0].Columns["PC_NAME"]);
s = s + "\n <table>";
s = s + "\n <tr>";
s = s + "\n <td class='br4'> ";
s = s + "\n <table>";
s = s + "\n <tr>";
s = s + "\n <td>";
s = s + "\n <ul id='qm0' class='qmmc'>";
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["PC_NAME"] == DBNull.Value)
{
s = s + "\n <li><a class='qmparent' href='#'>" + dr["C_NAME"].ToString() + "</a>";
s = s + "\n <ul>" + PopulateTree(dr) + "</ul>";
}
}
s = s + "\n <li class='qmclear'> </li></ul>";
s = s + "\n <script type='text/javascript'>qm_create(0,true,0,500,'all',false,false,false,false);</script>";
s = s + "\n </td>";
s = s + "\n </tr>";
s = s + "\n </table>";
s = s + "\n </td>";
s = s + "\n </tr>";
s = s + "\n </table>";
Literal1.Text = s;
}
private String PopulateTree(DataRow dr)
{
String s = "";
String ss;
foreach (DataRow row in dr.GetChildRows("rsParentChild"))
{
s = s + " <li>" + row["C_NAME"].ToString() + "\n";
ss = PopulateTree(row);
if (ss != "")
s = s + " <ul>" + ss + "</ul></li>\n\n";
}
return s;
}

Categories

Resources