Dynamically created textbox c# - c#

I create textbox dynamically, but can't retrieve a value from created textbox. Anyone can explain to me what am I doing wrong?
HtmlGenericControl testes = new HtmlGenericControl("DIV");
testes.ID = "Div_Cabos_Rede";
testes.Attributes.Add("class", "col-md-12 letra");
testes.InnerHtml = "Cabos de rede";
TextBox Cabos_de_rede = new TextBox();
Cabos_de_rede.ID = "Txt_Cabos_Rede";
Cabos_de_rede.Attributes.Add("class", "col-md-12 form-control");
testes.InnerHtml = "Cabos de rede";
Body.Controls.Add(testes);
Body.Controls.Add(Cabos_de_rede);
This works fine almost fine (minor unrelated css problems), but when later I try to retrieve data from dynamically created textbox I get NULL value.
Here is my code to retrieve value:
TextBox testar = (TextBox)Body.FindControl("Txt_Cabos_Rede");
ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('" + testar + "');", true);

The main problem dealing with dynamically created control is you need to reload them back in either Page Init or Page Load event.
FYI: We normally use either Panel or PlaceHolder to load controls instead of Body tag, so that we can style them easily.
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:PlaceHolder runat="server" ID="PlaceHolder1" />
<asp:Button runat="server" ID="SubmitButton" Text="Submit" OnClick="SubmitButton_Click" />
<br />
Posted Value:
<asp:Label runat="server" ID="ResultLabel" />
</form>
</body>
</html>
Code Behind
public partial class Default : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
HtmlGenericControl testes = new HtmlGenericControl("DIV");
testes.ID = "Div_Cabos_Rede";
testes.Attributes.Add("class", "col-md-12 letra");
testes.InnerHtml = "Cabos de rede";
TextBox Cabos_de_rede = new TextBox();
Cabos_de_rede.ID = "Txt_Cabos_Rede";
Cabos_de_rede.Attributes.Add("class", "col-md-12 form-control");
testes.InnerHtml = "Cabos de rede";
PlaceHolder1.Controls.Add(testes);
PlaceHolder1.Controls.Add(Cabos_de_rede);
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
TextBox testar = FindControlRecursive(PlaceHolder1, "Txt_Cabos_Rede") as TextBox;
ResultLabel.Text = testar.Text;
}
// Custom method to search a control recursively
// in case it is nested inside other control.
// You can create it as an extension method if you would like.
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
}
I know you have a lot of questions. Before commenting on this question, please create a new project, and make this very simple code to work.

Related

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."

Invalid postback or callback argument. AutoPostBack is set and also !Page.IsPostBack in Page_Load

Im getting the following error when I click on any item in my ListBox:
Invalid postback or callback argument. Event validation is enabled
using in configuration or <%#
Page EnableEventValidation="true" %> in a page. For security
purposes, this feature verifies that arguments to postback or callback
events originate from the server control that originally rendered
them. If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
However, I've set AutoPostBack="True" in my ListBox and also in my DropDownList:
<%# Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeBehind="Form1.aspx.cs" Inherits="WebApplication1.Form1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="dropDown" runat="server" AutoPostBack="True" Height="19px" Width="226px">
</asp:DropDownList>
</div>
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" Height="349px" Width="501px" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" ></asp:ListBox>
<br />
</form>
</body>
</html>
and I've set if (!Page.IsPostBack) in my .cs code:
using System;
using System.Collections.Generic;
using System.Web.UI;
namespace WebApplication1
{
public partial class Form1 : System.Web.UI.Page
{
public ServiceReference1.WebService1SoapClient client= new ServiceReference1.WebService1SoapClient();
public localhost.WebService1 asd = new localhost.WebService1();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> igralci = new List<string>();
foreach (localhost.Igralec ig in asd.vrniVseIgralce())
{
igralci.Add(ig.id + ", " + ig.ime + ", " + ig.priimek + ", " + ig.letoRojstva + "\n");
}
ListBox1.DataSource = igralci;
ListBox1.DataBind();
List<string> klubi = new List<string>();
klubi.Add("Vsi klubi");
foreach (localhost.Klub ig in asd.vrniVseKlube())
{
klubi.Add(ig.naziv);
}
dropDown.DataSource = klubi;
dropDown.DataBind();
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
}
Anyone know how to get rid of the error?
The error it self says you need to add "<%# Page EnableEventValidation="true" %> " in page, like below :-
" <%# Page Language="C#" AutoEventWireup="false" EnableEventValidation="false" CodeBehind="Form1.aspx.cs" Inherits="WebApplication1.Form1" %>"
and the error gets sorted out.

Get value from my own web control

I write one example to create own control on ASP.NET Froms. The controls very simple- combobox and button. User need choose value and when after he submit the button, the value from combobox need display in label.
So. Code of my Control:
public class MyControl:Control,IPostBackEventHandler
{
protected override void Render(HtmlTextWriter writer)
{
writer.AddAttribute("size","1");
writer.AddAttribute("ID","List2");
writer.AddAttribute("name", "ListYear");
writer.RenderBeginTag(HtmlTextWriterTag.Select);
for (int i = 1950; i < DateTime.Now.Year; i++)
{
writer.RenderBeginTag(HtmlTextWriterTag.Option);
writer.WriteEncodedText(i.ToString());
writer.RenderEndTag();
}
writer.RenderEndTag();
writer.AddAttribute("type","submit");
writer.AddAttribute("value","ClickMe");
writer.AddAttribute("name","BtnChange");
writer.RenderBeginTag(HtmlTextWriterTag.Input);
writer.RenderEndTag();
base.Render(writer);
}
public delegate void OnClickEventHandler(object sender, EventArgs args);
public event OnClickEventHandler Click;
public void RaisePostBackEvent(string eventArgument)
{
Click(this, new EventArgs());
}
}
The Page ASP:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestMyControl.aspx.cs" Inherits="Hello.TestMyControl" %>
<%# Register assembly="Hello" namespace="Hello" tagPrefix="MyContrl" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
<br />
<MyContrl:MyControl runat="server" OnClick="Unnamed1_OnClick" ID="Control1"></MyContrl:MyControl>
</div>
</form>
</body>
</html>
And in the end Event function:
protected void Unnamed1_OnClick(object sender, EventArgs args)
{
Label1.Visible = true;
Label1.Text="You choose "+Control1.????+" year";
}
What substitute for a question mark that take the value from the list?
P.S. Something strange is going on. Because when I click the button, the handler is not called, and I can not get into Unnamed1_OnClick
Since you have set the value on an attribute, to retrieve it you need to access Attributes property
Make your control inherit from HtmlControl
public class MyControl : HtmlControl, IPostBackEventHandler
{
...
On your page
<MyContrl:MyControl runat="server" OnClick="Unnamed1_OnClick" ID="Control1"></MyContrl:MyControl>
On your code
Label1.Text = Control1.Attributes["value"];
You can debug this line to see all available attributes
You would need to pass the name of the combobox and its the value of the text that is selected.
Like this:
protected void Unnamed1_OnClick(object sender, EventArgs args)
{
Label1.Visible = true;
Label1.Text="You choose "+ myCustomControl.SelectedItem.Value.ToString()
+ " year";
}
(Sorry. I misread the initial post and edited my code accordingly once I realized my mistake.)
Add select list to your user control with name="YourSelectList"
then in the click event handler
protected void Unnamed1_OnClick(object sender, EventArgs args)
{
Label1.Visible = true;
Label1.Text="You choose "+Control1.YourSelectList.SelectedValue.ToString()+" year";
}

Access a textbox in C# that is created on fly

My code generates an TextBox on the fly in C# (page_load function). Can I access it in the code later? It does give me compilation error and does not seem to work. Can someone verify ?
Code for additonal problem
aContent += "<table>";
aContent += "<tr><td>lablel </td><td style='bla blah'><input type='textbox' id='col-1' name='col-1'/></td></tr> ... 10 such rows here
</table>"
spanMap.InnerHtml = aContent;
The contents are rendered OK but recusrive iteration does not return the textbox. I am calling it like this
TextBox txt = (TextBox)this.FindControlRecursive(spanMap, "col-1");
// txt = (TextBox) spanMapping.FindControl("col-1"); this does not work too
if (txt != null)
{
txt.Text = "A";
}
Assuming that you're persisting it correctly, you should be able to access it in code-behind using the FindControl method. Depending on where the control is, you may have to search recursively through the control hierarchy:
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
Using FindControlRecursive:
TextBox txt = this.FindControlRecursive(Page.Form, "TextBox1") as TextBox;
if (txt != null)
{
string text = txt.Text;
}
If you still can't find it using the above method, make sure that you're creating the control during after every postback, somwhere before Page_Load, like OnInit.
EDIT
I think you need to change the way you're adding content to the container. Instead of using a <span>, I would use a Panel, and instead of building markup, simply add controls to the panel in code-behind:
TextBox txt = new TextBox();
txt.ID = String.Format("txt_{0}", Panel1.Controls.Count);
Panel1.Controls.Add(txt);
Here's an example:
<%# Page Language="C#" %>
<script type="text/C#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
var textBox = new TextBox();
textBox.ID = "myTextBox";
textBox.Text = "hello";
Form1.Controls.Add(textBox);
}
protected void BtnTestClick(object sender, EventArgs e)
{
var textBox = (TextBox)Form1.FindControl("myTextBox");
lblTest.Text = textBox.Text;
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<asp:LinkButton ID="btnTest" runat="server" Text="Click me" OnClick="BtnTestClick" />
<asp:Label ID="lblTest" runat="server" />
</form>
</body>
</html>

Deleting a directory when clicked on a hyperlink

I want to delete a directory when its clicked on a hyperlink.I tried like the below.But my page redirecting to default(start) page and the directory is not deleting.
protected void Page_Load(object sender, EventArgs e)
{
Execute(s,Content,k,j);
}
private void Execute(string path,string cont,string sym,string space )
{
foreach (var directory in new DirectoryInfo(path).GetDirectories())
{
string f = directory.FullName;
f = Server.UrlPathEncode(f);
Response.Write("<a href =''" + "onclick='Delete(" + f + ")'> DELETE </a>");
Execute(directory.FullName,cont1,sym1,space1);
}
}
private void Delete(string path)
{
DirectoryInfo DirDel = new DirectoryInfo(path);
DirDel.Delete();
}
Can you tell me the problem in this code?
It is not clear from your question, where you have that folder, if it is on the client side, then i think it is not possible.
If it is on the server side you could use a link button instead of an anchor tag to run the code behind function
If you cant use the link button for some reason you could use JavaScript ajax calls to call the code behind function.
Here is a code project article, that may help you
You're rendering clientside code, expecting it to call serverside code. This will never work, clientside always happens on their machine, not on your server.
What you want is to use a LinkButton control, e.g.:
<%# Page Language="C#" AutoEventWireup="True" %>
<!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>
<title>LinkButton Example</title>
<script language="C#" runat="server">
protected void LinkButton_Click(Object sender, EventArgs e)
{
// Code to delete directory
}
</script>
</head>
<body>
<form id="form1" runat="server">
<h3>LinkButton Example</h3>
<asp:LinkButton id="LinkButton1"
Text="Click Me"
Font-Names="Verdana"
Font-Size="14pt"
OnClick="LinkButton_Click"
runat="server"/>
<br />
<asp:Label id="Label1" runat="server" />
</form>
</body>
</html>
The general problem is that you create client-side URLs, but method to call is server-side. So you need to create server-side URLs, and handle postback click:
string path = #"d:\Temp";
protected override void OnInit(EventArgs e)
{
string dir = this.Request["dir"];
if (String.IsNullOrEmpty(dir)) // write links
{
foreach (var di in new DirectoryInfo(path).EnumerateDirectories())
{
var link = new HyperLink()
{
Text = di.Name,
NavigateUrl = String.Format("?dir={0}", HttpUtility.UrlEncode(di.Name))
};
this.Controls.Add(link);
}
}
else // process link click
{
dir = HttpUtility.UrlDecode(dir);
path = Path.Combine(path, dir);
Directory.Delete(path);
Response.Redirect("~/Default.aspx"); // page's name to refresh content
}
}
You should use a LinkButton to get the same look as the , but you need your code to be execute on server side as the PostBack for your LinkButton.
The code you have here will make a call to a client-side script.

Categories

Resources