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?
Related
I tried to create dynamic buttons after clicked on "searchbutton". But I always get returned to the homePage and do not enter the BtnBuy_ServerClick function.
GetPostBackControl() - return null if don't found control, else the control.
See at the end the adding and creating of buttons.
I am glad for any help with that issue.
Thank you!
public partial class HomePageDesignaspx : System.Web.UI.Page
{
private static List<Button> buttonList;
protected void Page_Load(object sender, EventArgs e)
{
if (buttonList != null)
{
for (int i = 0; i < buttonList.Count(); i++)
{
buttonList[i].Click += new EventHandler(this.BtnBuy_ServerClick);
}
}
else
{
buttonList = new List<Button>();
}
Control c = GetPostBackControl(Page);
if (c != null && c.ID == "SearchBtn")
{
DataBase db = DataBase.Instance;
flights = db.GetFlights(companyValue, sourceValue, destinationValue, date, minPriceS, maxPriceS);
for (int i = 0; i < flights.Count; i++)
{
if (i % 3 == 0)
{
HtmlGenericControl drow = new HtmlGenericControl("div");
drow.ID = "drow" + i.ToString();
drow.Attributes.Add("class", "row");
this.flightTable.Controls.Add(drow);
}
HtmlGenericControl dCol = new HtmlGenericControl("div");
dCol.ID = "dCol" + i.ToString();
dCol.Attributes.Add("class", "col-sm-4");
this.flightTable.Controls.Add(dCol);
HtmlGenericControl dCard = new HtmlGenericControl("div");
dCard.ID = "dCard" + i.ToString();
dCard.Attributes.Add("class", "card-section");
dCol.Controls.Add(dCard);
HtmlGenericControl dCardImg = new HtmlGenericControl("div");
dCardImg.ID = "dCardImg" + i.ToString();
dCardImg.Attributes.Add("class", "card-section-image");
dCard.Controls.Add(dCardImg);
HtmlGenericControl CardImg = new HtmlGenericControl("img");
CardImg.ID = "CardImg" + i.ToString();
CardImg.Attributes.Add("src", "../Images/plane2.jpg");
dCardImg.Controls.Add(CardImg);
HtmlGenericControl dCardDesc = new HtmlGenericControl("div");
dCardDesc.ID = "dCardDesc" + i.ToString();
dCardDesc.Attributes.Add("class", "card-desc");
dCard.Controls.Add(dCardDesc);
HtmlGenericControl dCardTitle = new HtmlGenericControl("div");
dCardTitle.ID = "dCardTitle" + i.ToString();
dCardTitle.Attributes.Add("class", "title");
dCardDesc.Controls.Add(dCardTitle);
HtmlGenericControl H5Title = new HtmlGenericControl("h5");
H5Title.ID = "H53Title" + i.ToString();
H5Title.Attributes.Add("class", "card-desc");
H5Title.InnerText = "Num flight is " + flights[i].Id;
dCardTitle.Controls.Add(H5Title);
HtmlGenericControl dCardInfo = new HtmlGenericControl("div");
dCardInfo.ID = "dCardInfo" + i.ToString();
dCardInfo.Attributes.Add("class", "card-info");
dCardDesc.Controls.Add(dCardInfo);
HtmlGenericControl UlList = new HtmlGenericControl("ul");
UlList.ID = "UlList" + i.ToString();
UlList.Attributes.Add("class", "list-unstyle");
dCardInfo.Controls.Add(UlList);
HtmlGenericControl LiDate = new HtmlGenericControl("li");
LiDate.ID = "LiDate" + i.ToString();
UlList.Controls.Add(LiDate);
HtmlGenericControl iDate = new HtmlGenericControl("i");
iDate.ID = "iDate" + i.ToString();
iDate.Attributes.Add("class", "far fa-calendar-alt");
LiDate.Controls.Add(iDate);
HtmlGenericControl LabelDate = new HtmlGenericControl("label");
LabelDate.ID = "LabelDate" + i.ToString();
LabelDate.InnerText = "Date: " + flights[i].DateFlight;
LiDate.Controls.Add(LabelDate);
HtmlGenericControl LiPlace = new HtmlGenericControl("li");
LiPlace.ID = "LiPlace" + i.ToString();
UlList.Controls.Add(LiPlace);
HtmlGenericControl iPlace = new HtmlGenericControl("i");
iPlace.ID = "iPlace" + i.ToString();
iPlace.Attributes.Add("class", "fas fa-map-marker-alt");
LiPlace.Controls.Add(iPlace);
HtmlGenericControl LabelPlace = new HtmlGenericControl("label");
LabelPlace.ID = "LabelPlace" + i.ToString();
LabelPlace.InnerText = "Place: " + flights[i].Source + "->" + flights[i].Destination;
LiPlace.Controls.Add(LabelPlace);
HtmlGenericControl LiPrice = new HtmlGenericControl("li");
LiPrice.ID = "LiPrice" + i.ToString();
UlList.Controls.Add(LiPrice);
HtmlGenericControl iPrice = new HtmlGenericControl("i");
iPrice.ID = "iPrice" + i.ToString();
iPrice.Attributes.Add("class", "fas fa-hand-holding-usd");
LiPrice.Controls.Add(iPrice);
HtmlGenericControl LabelPrice = new HtmlGenericControl("label");
LabelPrice.ID = "LabelPrice" + i.ToString();
LabelPrice.InnerText = "Price: " + flights[i].Price;
LiPrice.Controls.Add(LabelPrice);
Button BtnBuy = new Button();
BtnBuy.ID = flights[i].Id;
BtnBuy.Attributes["class"] = "cart_btn btn btn-dark";
BtnBuy.Attributes.Add("type", "submit");
BtnBuy.Text = "Buy Now";
buttonList.Add(BtnBuy);
BtnBuy.Click += new EventHandler(this.BtnBuy_ServerClick);
UlList.Controls.Add(BtnBuy);
}
}
}
}
void BtnBuy_ServerClick(object sender, EventArgs e)
{
string buttonId = ((HtmlButton)sender).ID;
Session["IdFlight"] = buttonId;
Server.Transfer("~/WebPage/BuyFlight.aspx");
}
ASPX Markup in homePage.aspx:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<section class="card">
<div class="row" id="flightTable" runat="server">
<!--Place for tickets after the search-->
</div>
</section>
* I have GridView in dynamic..i want to change the dynamic value into hyperlink..here is my code*
foreach (GridViewRow gr in Gridview1.Rows)
{
HyperLink hp = new HyperLink();
hp.Text = gr.Cells[25].Text;
hp.NavigateUrl = "https://chennaiuat.paynearby.in:2025/UploadFiles/SDFiles/DepositSlip/" + hp.Text;
hp.Text = "<a href='" + hp.NavigateUrl+"'> </a>";
gr.Cells[25].Text = hp.Text;
}
Change your code in this way:
hp.Text = Context.Server.HtmlDecode("<a href='" + hp.NavigateUrl+"'> </a>");
Convert input field string in the table to the input field?
<%= HttpUtility.HtmlDecode((string)objRow["Post"]) %>
On view End
<%= HttpUtility.HtmlDecode(GetUsersList())%>
Code In Cs File
foreach (DataRow dtRow in ds.Tables[0].Rows)
{
string userpk = Convert.ToString(dtRow["user_pk"]);
string usertypecd = Convert.ToString(dtRow["user_type_cd"]);
string firstname = Convert.ToString(dtRow["first_name"]);
string lastname = Convert.ToString(dtRow["last_name"]);
string active = Convert.ToString(dtRow["active_ind"]);
if (active == "true")
{
active = "< input type = 'checkbox' class='editor-active' disabled='disabled' checked='checked'>";
}
else {
active = "< input type = 'checkbox' class='editor-active' disabled='disabled'>";
}
string phoneno = Convert.ToString(dtRow["phone_no"]);
string phone_ext = Convert.ToString(dtRow["phone_ext"]);
string email = Convert.ToString(dtRow["email"]);
content += "<tr><td>"+ usertypecd+ "</td><td>" + firstname + "</td><td>" + lastname + "</td><td>" + active + "</td><td>" + phoneno + "</td><td>" + phone_ext + "</td><td>" + email + "</td><td></td></tr>";
}
return content;
Result Image:
If you mean Asp-WebForms you can create a System.Web.Label with the html text in the Text Property. This will then render as HTML if you add the control to your page.
Alternatively you can just dump the text into a protected/public property and use <%= YourPropertyNameHere %> to dump the text as it is into the page.
Personally through I recommend you build your web controls instead of string operations. For example create a System.Web.Panel and then add your html controls to it as you need them.
var pnl = new Panel();
var cb = new CheckBox();
cb.Enabled = (active == "true");
cb.Checked = cb.Enabled;
cb.CssClass = "editor-active";
pnl.Controls.Add(cb);
SomePanelInFrontCode.Controls.Add(pnl);
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);
}
}
}
I have a piece of code that creates dynamic controls using 2 while loops.
As you can see, I am forced to declare both LiteralControls INSIDE each while loop because if I don't, the puBugList.Controls.Add(lineBreak) will not acknowledge.
Q: Why can I not see the scope of the controls from inside a while loop?
//this control is not acknowledged
//LiteralControl lineBreak = new LiteralControl("<br/>");
while (nwReader.Read())
{
int id = (int)nwReader["bid"];
string user = (string)nwReader["buname"];
string prob = (string)nwReader["bproblem"];
string content = id + ". " + user + ": " + prob + "<br/>";
Label lb = new Label();
lb.Text = content;
phBugList.Controls.Add(lb);
//forced to declare 1 here
LiteralControl lineBreak = new LiteralControl("<br/>");
String sqlSelRep = "SELECT * FROM [reply] WHERE bid=#bid";
SqlCommand cmdSelRep = new SqlCommand(sqlSelRep, conn);
cmdSelRep.Parameters.AddWithValue("#bid", id);
SqlDataReader repReader = cmdSelRep.ExecuteReader();
while (repReader.Read())
{
//forced to declare another
LiteralControl lineBreak2 = new LiteralControl("<br/>");one here
string msg = (string)repReader["rmsg"];
Label lbRep = new Label();
lbRep.Text = "Admin: \"" + msg + "\"";
phBugList.Controls.Add(lbRep);
phBugList.Controls.Add(lineBreak2);
}
repReader.Close();
if (Convert.ToInt32(Session["user"]) == 1)
{
phBugList.Controls.Add(lineBreak);
TextBox tbRep = new TextBox();
tbRep.ID = "tb" + id.ToString();
phBugList.Controls.Add(tbRep);
LinkButton butRep = new LinkButton();
butRep.ID = "rep" + id.ToString();
butRep.Text = " Reply";
butRep.Click += InsertReply;
phBugList.Controls.Add(butRep);
LinkButton butDel = new LinkButton();
butDel.ID = "del" + id.ToString();
butDel.Text = " Delete";
butDel.Click += DeleteBug;
phBugList.Controls.Add(butDel);
phBugList.Controls.Add(lineBreak);
}
phBugList.Controls.Add(lineBreak);
}
I think you'r problem is that if you instantiate LiteralControl outside the while loop you are effectively using the same object throughout your code, and you cannot add the same control twice to a Controls collection of another control.
Try the following:
LiteralControl lineBreak = null;
(...)
while (repReader.Read())
{
literalControl = new LiteralContro(...);
}
Anyway, unless you need lineBreak in scope outside the while loop there is nothing wrong declaring the variable inside the loop so your code is perfectly fine.