Dynamic Div creation asp.net - c#

I am trying to create Div dynamically on the press of button click.
For that i refered this link>> http://forums.asp.net/t/1349244.aspx
and made code on server side(.cs page) as follows>>
public static int i = 0;
protected void Button1_Click(object sender, EventArgs e)
{
i++;
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "NEWControl"+i;
newControl.InnerHtml = "This is a dynamically created HTML server control.";
PlaceHolder1.Controls.Add(newControl);
}
This code was giving me just one div each time when i press the button., I wanted to have addition of divs.
On client side using javascript also i tried>>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick="addDiv();" />
</div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</form>
</body>
</html>
<script type="text/javascript">
function addDiv() {
alert("Control comming in function");
var r = document.createElement('Div');
r.style.height = "20px";
r.style.width = "25px";
r.appendChild("div");
alert("Control going out of function");
}
</script>
Both of these didnt work.
What mistake am i making?
Is there any thing wrong?

Use this
public int Index
{
get
{
if(ViewState["Index"]==null)
{
ViewState["Index"]=0;
}
else
{
ViewState["Index"]=int.Parse(ViewState["Index"].ToString())+1;
}
return int.Parse(ViewState["Index"].ToString());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "NEWControl"+Index;
newControl.InnerHtml = "This is a dynamically created HTML server control.";
PlaceHolder1.Controls.Add(newControl);
}

It is giving you one div, cause you are adding one div.
Remember that asp.net needs you to create all dynamically added controls on very PostBack after that.
If you want two controls you have to add two to the PlaceHolder.

Just use one parent div with some ID(predefined lets say id="dvDynamic") and runat="server"
and then use it the dvDynamic.innerHTML = "<div> /* dynamic div contents */ </div>"
Its the simplest way, as if you are using html element in ASP.net use dom controls for better generation. Dynamic creation of control will require handled, interface and many things to co-ordinate with that control. As its not predefined by system. you have to create it.
SO choose the DOM element option. that is faster and better :)
I hope this will help :)

Related

add multiple innerhtml in asp.net

my x.aspx file :-
<form id ="Content3ret" runat="server">
</form>
<asp:Button ID="Button1" runat="server" OnClick ="Button1_Click"/>
my x.aspx.cs file :-
protected void Button1_Click(object sender, EventArgs e)
{
var x = Guid.NewGuid().ToString();
Content3ret.innerhtml = "<table id = '"+x+"'> <tr> <td><input type='radio' name='radiotest' checked='checked'/></td> </tr> </table>";
}
what I am trying to do is :-
when I click button each and every time there should be new radio button added with other .
like 3 button click I need 3 radio button .
but with this code when I click only one radio button creating .
like 3 click only one radio button with new id.
can anyone help me ?
When you add data on Content3ret.innerhtml and render them on the pages, this data are lost / gone / stay on page and never come back on post back - because this inner html is not post back with the second click on button.
So you have to render them on page, and at the same time saved it somewhere - preferable on viewstate because of asp.net
so the page will be like
<form id="form1" runat="server">
<div runat="server" id="divPlaceOnme"></div>
<asp:Button ID="Button1" runat="server" Text="ok" OnClick ="Button1_Click"/>
</form>
and on code behind we have
const string InnerHtmlKeeper_name = "InnerHtmlKeeper_cnst";
string InnerHtmlKeeper
{
get
{
var RetMe = ViewState[InnerHtmlKeeper_name] as string;
if (string.IsNullOrEmpty(RetMe))
return string.Empty;
else
return RetMe;
}
set
{
ViewState[InnerHtmlKeeper_name] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var x = Guid.NewGuid().ToString();
// we keep the new with the previous data on this ViewState
InnerHtmlKeeper += "<table id = '" + x + "'> <tr> <td><input type='radio' name='radiotest' checked='checked'/></td> </tr> </table>";
// we add the final render on the div on page
divPlaceOnme.InnerHtml = InnerHtmlKeeper;
}
Last words.
Your approaches have many issues - and your code not working as it is. The button must be on the form, and you have to render inside some other div.
The point here is to show you have to save some actions on viewstate - beside that for a good solution on your problem you must use some javascript to render the radio without post back.

dynamically load a user control in the aspx page

I have the following aspx page for eg: called choosemenu.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<div id="renderhere" runat="server">render user control here </div>
</form>
</body>
</html>
I have a list of ascx pages called
english.ascx
commerce.ascx
maths.ascx
I have to dynamically load the ascx files in my aspx page depending on the querystring in the aspx page.
I have the following contents in my aspx page in page_load event.
var control = (English)Page.LoadControl("/ascx/english.ascx");
How will I render the contents of the english.ascx page in the choosemenu.aspx that too in this tag
Also I have to pass some value in the ascx file. This is the static stuff.
<Menu:MNU ID="english" runat="server" HiLiter="<%#h %>"></Menu:MNU>
Loading a control from the server side
protected void Page_Load(object sender, EventArgs e)
{
Page.Controls.Add(Page.LoadControl("~/ascx/english.ascx")); //CHECK THE PATH
}
Loading a control from the server side and rendering it into a div
If you want to render it in a specific div you might write:
protected void Page_Load(object sender, EventArgs e)
{
UserControl uc = (UserControl)Page.LoadControl("~/ascx/english.ascx");
uc.MyParameter = 1;
uc.Id = 2;
uc.someMethodToInitialize();
div1.Controls.Add(uc);
}
and in your aspx page:
<div id="div1" runat="server">
</div>
Loading a control from the server side initializing the control with parameters
If your control has a constructor with parameters, you have to use:
public English_Control(int MyParameter, int Id)
{
//code here..
}
In you aspx.cs file you can initialize with:
UserControl uc = (UserControl)Page.LoadControl(typeof(English_Control), new object[] {1, 2});
div1.Controls.Add(uc);
In order for the control's postback values to be available, you must load and reload it no later than PreInit. Here is the code you need to do that.
protected override void OnPreInit(EventArgs e)
{
string controlToLoad = String.Empty;
//logic to determine which control to load
UserControl userControl = (UserControl)LoadControl(controlToLoad);
renderhere.Controls.Add(userControl);
base.OnPreInit(e);
}
As per MSDN:
Pre-Init event used to "Create or re-create dynamic controls."

A pragmatical point of view to ASP.NET's page cycle

I have a form like the following:
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="plcHolder" runat="server">
</asp:PlaceHolder>
<asp:Button ID="btnSubmit" Text="submit" runat="server"
onclick="btnSubmit_Click" />
</div>
</form>
And here is my code:
protected string FetchDataFromDatabase()
{
return "some long string";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.plcHolder.Controls.Add(new Label() { Text = FetchDataFromDatabase() } );
}
}
Page_Load() gets a long string from the database.
protected void btnSubmit_Click(object sender, EventArgs e)
{
this.plcHolder.Controls.Add(new Label() { Text = "new text" });
}
My Button adds new text to my page. However, when I click the button, I only see the string "new text" but I was looking for both texts ("some long string new text") instead.
I don't want to call my database at every button click since the text already loaded to the page. How do I achieve this?
I know that this example seems a little weird, it's because I tried to give the minimal working example.
In the load, when you get the value from the database, store it in Session:
Session["textFromDatabase"] = GetTextFromDatabase();
and then leverage that value in both places. So if you were in the click you would say:
... Text = Session["textFromDatabase"] + " new text";
and now you can get the value from the database when it's not a post back, just once like you stated, but leverage it over and over.
And I'm pretty sure, based on what you said, this is the inverse of the condition you want, throw a ! in front of it:
if (Page.IsPostBack)

How to enable javascript in asp.net webforms

i am trying to use javascript events in asp.net webforms. but events for input controls like textfield, such as onClick, onFocus,onBlur, dont appear. do i need to change my directive:
<%# Page Title="" Language="C#" MasterPageFile="~/YourGuruMaster.master" AutoEventWireup="true" CodeFile="AskQuestion.aspx.cs" Inherits="AskQuestion" %>
i want to be able to do this:
//code page
protected void Page_Load(object sender, EventArgs e)
{
QuestionTextBox1.Attributes["onfocus"] = "ClearSearchText()";
//Markup page
function ClearSearchText() {
var searchUserName = document.getElementById('<%=QuestionTextBox1.ClientID%>');
if (searchUserName.value = searchUserName.defaultValue) {
searchUserName.value = "";
}
return false;
}
<p dir="rtl" style="">
<asp:TextBox ID="QuestionTextBox1" runat="server" Width="702px"
Text="פרטים עד 5000 תווים"></asp:TextBox>
Add onfocus and onblur into the markup as follows:
<asp:TextBox ID="TextBox1" runat="server" onfocus="TextBox1_focus(this, event)" onblur="TextBox1_blur(this, event)" Text="Search..."></asp:TextBox>
<script type="text/javascript">
var searchText = 'Search...';
function TextBox1_focus(sender, e) {
if (sender.value == searchText)
sender.value = '';
}
function TextBox1_blur(sender, e) {
if (sender.value == '')
sender.value = searchText;
}
</script>
Well, not sure which ASP.NET version you use. I think last versions allow this (rendering attributes that the server controls don't understand to the browser still). Try using "onfocus" instead (lower case).
However, if this is not working for you, then you have to do it from code behind...
protected void Page_Load(object sender, EventArgs e)
{
QuestionTextBox1. Attributes["onfocus"]="someJavaScriptMethod";
}
Alternatively, if you have jQuery in the page you can go something like ...
<script type="text/javascript">
$(function() {
$('#<%= QuestionTextBox1.ClientID %>').focus(someJavaScriptMethod);
});
</script>
If you do that, inside someJavaScriptMethod(), you can use the word this to point at the focused control, and you can create a jQuery object from it easily like $(this).
.
Please leave me a comment if none of the above solves your problem.

UpdatePanel Breaks JQuery Script

This is a simplified version of what I want to do. Basically I have a datalist with a bunch of stuff in it and when you mouseover items in the datalist I want jquery to hide/show stuff. The problem is that after I databind my gridview/repeater/datalist jquery quits working if the gridview/repeater/datalist is in an update panel.
After you click the button in the sample below, the jquery that makes the span show up when you mouse over quits working.
Any ideas of why this is happening, how to fix it or a better way to do this?
<script type="text/javascript">
$(document).ready(function() {
$('.comment-div').mouseenter(function() {
jQuery("span[class=mouse-hide]", this).fadeIn(50);
});
$('.comment-div').mouseleave(function() {
jQuery("span[class=mouse-hide]", this).fadeOut(50);
});
});
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="comment-div">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<span class="mouse-hide" style="display: none;">sdfgsdfgsdfgsdfg</span>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
And the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindStuff();
}
}
public void BindStuff()
{
TestDB db = new TestDB();
var x = from p in db.TestFiles
select new { p.filename};
x = x.Take(20);
GridView1.DataSource = x;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
BindStuff();
}
The reason this is happening is because the controls get recreated on a partial postback. Use the 'live' feature of jQuery so rewrite your code like:
$(document).ready(function() {
$('.comment-div').live('mouseenter',function() {
jQuery("span[class=mouse-hide]", this).fadeIn(50);
});
$('.comment-div').live('mouseleave', function() {
jQuery("span[class=mouse-hide]", this).fadeOut(50);
});
});
When the UpdatePanel refreshes, it completely replaces all of the DOM elements that you had previously attached event handlers to. The easiest fix is to initialize your event handlers in pageLoad() instead of $(document).ready(). Its code will be executed both on the initial page load, but also after every UpdatePanel refresh.
The better solution is to change your code to use live() or delegate(), so that the event handlers aren't impacted by periodic changes in the page's contents.
When you do a AJAX postback using an update panel the DOM within it's removed and re-created when the AJAX response arrive.
The handlers you attached are lost unless you use the live method or the livequery library
See below for different jQuery versions:
$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+

Categories

Resources