How to add span & inside that control dynamically in c# - c#

I want to add span & inside that span I want to add control.
Both have to be added dynamically using code in c#.
I know how to add span but how to add control inside that span ?
Code to add span & control are
var a = new HtmlGenericControl("span");
a.InnerHtml = "Something";
a.Attributes["class"] = "validation-asterix";
pn.Controls.Add(a);
RequiredFieldValidator rfv = new RequiredFieldValidator {
ControlToValidate = "txt" + txField.ColumnName,
Display = ValidatorDisplay.Dynamic,
Text = "*",
ID = "val" + txField.ColumnName,
Visible = true,
};
pn.Controls.Add(rfv);
I want to add above span which will have this requiredfieldvalidator dynamically.

What I will do is to create a void ContentPlaceHolder in the markup code, in the place that you want to show the validation error message.
Then, from codebehind, you simply can add the validator as:
RequiredFieldValidator rfv = new RequiredFieldValidator {
ID = "val" + txField.ColumnName,
ControlToValidate = "txt" + txField.ColumnName,
Display = ValidatorDisplay.Dynamic,
Text = "*",
CssClass = "validation-asterix"
};
ContentPlaceHolderID.Controls.Add(rfv);
Not need to use any span here.

Related

Placeholder.FindControl() only identifying the first control in placeholder and NULL returns for other controls?

I am developing a website by using ASP.NET.
I have a placeholder to dynamically show controls.
Here is my ASPX code for that.
<asp:PlaceHolder runat="server" ID="pHolderTest"></asp:PlaceHolder>
From code behind I use this code to generate controls inside placeholder.
RadioButton rdbTest1 = new RadioButton() { Text = "&nbsp Test1", GroupName = "my", ID = "rdbTest1", Checked = true };
pHolderTest.Controls.Add(rdbTest1 );
pHolderTest.Controls.Add(new Literal() { Text = "</br>" });
RadioButton rdbTest2 = new RadioButton() { Text = "&nbsp Test2", GroupName = "my", ID = "rdbTest2" };
pHolderTest.Controls.Add(rdbTest2);
pHolderTest.Controls.Add(new Literal() { Text = "</br>" });
//----So on
So when a user select a particular radiobutton in this placeholder I want to get what user is clicked. So to do that I used this code.
RadioButton rdbTest1 = pHolderTest.FindControl("rdbTest1") as RadioButton;
RadioButton rdbTest2 = pHolderTest.FindControl("rdbTest2") as RadioButton;
if (rdbTest1.Checked)
{
//--Code
}
else if (rdbTest2.Checked)
{
//--Code
}
So everythings ok. But probelem is When I findcontrols inside placeholder It only getting the first radiobutton (rdbTest1) and after that other controls getting NULL values. I am calling to my dynamic controls generating function on Page_Load event to retain my Placeholder when every PostBack. I am only getting the value of the first radiobutton. So how to find my all controls inside the placeholder?

basic html tags inside code behind

Is it possible to insert bold tag in a Control.Text? Here's my code:
Label lab_Name = new Label();
Label lab_actualName = new Label();
lab_Name.Text = "Name: ";
lab_Name.Style.Add("font-weight", "bold");
lab_actualName.Text = + allRecords[i].name;
because I want it to be something like this:
<b>Name: </b> Bosiyan
but I don't want to separate them and here's what I've been thinking(if possible):
Label lab_Name = new Label();
//lab_Name.Text = "<b>Name: </b>" + allRecords[i].name;
You can use ASP.NET Literal for that purpose
Literal lit_Name = new Literal();
lit_Name.Text = "<b>Name: </b> Bosiyan";
and the text will be rendered as it is, i.e Name: will be bold as below
Name: Bosiyan
You can also define the Literal control in aspx like this
<asp:Literal ID="lit_Name" runat="server" />
and set the Text property in code behind without initializing lit_Name
lit_Name.Text = "<b>Name: </b> Bosiyan";
You can use two labels. So basically anything you want to mark as bold you can use controlstyle as all controls have that property
Label a = new Label() { Text= "test"};
a.ControlStyle.Font.Bold = true;

Unable to find control with id when using the panel RenderControl Method

I am trying to dynamically create a form in asp.net and render it out on the page by performing a text replace on the rendered controls.
(I cannot just push the controls to a panel on the page, that would be the ideal situation and I wouldn't be having this problem right now)
I create a label, textbox and a button and add them all to a panel. This panel is then rendered into a string using a TextWriter, which I then to use perform my replace on my copy.
Label lbl = new Label();
lbl.Text = "Enter Amount";
lbl.Attributes.Add("style", "width:25%; vertical-align:middle;");
lbl.CssClass = "donate-label";
lbl.ID = "lblAmount";
TextBox tb = new TextBox();
tb.ID = "tbAmount";
tb.Attributes.Add("style", "padding-left:25px; width:50%;");
lbl.AssociatedControlID = tb.ID;
Button b = new Button();
b.ID = "btnDonate";
b.Text = "Make a Donation";
b.CssClass="block-btn right-arrow red-bg right";
b.Click += new EventHandler(btnDonate_Click);
b.Attributes.Add("style", "display:table-cell; margin-top:0; width:40% !important;");
Panel pnlForm = new Panel();
pnlForm.CssClass="form clearfix donate-form";
pnlForm.Attributes.Add("style", "width:70%");
pnlForm.Controls.Add(lbl);
pnlForm.Controls.Add(tb);
pnlForm.Controls.Add(b);
Now if I was to add the above panel to a panel that already existed on the page, it would work perfectly and as expected, but the control rendering is causing it to break somewhere..
TextWriter myTextWriter = new StringWriter();
HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);
pnlForm.RenderControl(myWriter);
string body = p.Copy.Replace("##donate##", myTextWriter.ToString());
The error I get is as follows:
Unable to find control with id 'tbAmount' that is associated with the Label 'lblAmount'.
Line 146: pnlForm.RenderControl(myWriter);
If I removed the assoicatedControlID for my label it works fine, but unfortunately it renders my label as a span which isn't what I need, I need it rendered as a label with a 'for' attribute.
The easiest way is to use literal with html tags inside it
Literal lbl = new Literal();
lbl.Text = "<Label For='tbAmount' style='width:25%; vertical-align:middle;' class='donate-label' > Enter Amount </label>";
lbl.ID = "lblAmount";
by the way make the tbAmount id static so you dont get any unpredictable id for your textbox
tb.ClientIDMode= System.Web.UI.ClientIDMode.Static

RequiredFieldValidator not working in a repeater

I'm trying to dynamically add a RequiredFieldValidator to a RadioButtonList in a repeater, but it fails with the error:
Unable to find control id 'rblAccessory_40' referenced by the 'ControlToValidate' property of ''.
The code for this section is:
if ((e.Item.ItemType != ListItemType.Header) && (e.Item.ItemType != ListItemType.Footer))
{
Label lblAccID = (Label)e.Item.FindControl("lblAccID");
RadioButtonList rblCondition = (RadioButtonList)e.Item.FindControl("rblCondition");
rblCondition.ID = "rblAccessory_" + lblAccID.Text;
if (conditionList.Count() > 0)
{
RequiredFieldValidator rfv = new RequiredFieldValidator();
rfv.ControlToValidate = "rblAccessory_" + lblAccID.Text;
rfv.ErrorMessage = "Please complete the accessories section";
pnlValidation.Controls.Add(rfv);
rblCondition.DataSource = conditionList;
rblCondition.DataValueField = "id";
rblCondition.DataBind();
}
foreach (ListItem li in rblCondition.Items)
{
li.Text = "";
li.Value = "AccessoryID_" + lblAccID.Text + "-ConditionID_" + li.Value;
}
}
}
It is definitely finding the RadioButtonList (rblCondition) because the data is binding correctly at this point:
rblCondition.DataSource = conditionList;
rblCondition.DataValueField = "id";
rblCondition.DataBind();
So I don't understand why the error says it is unable to find the control ID.
I've tried specifying the control ID manually, as below:
rfv.ControlToValidate = "rblAccessory_" + lblAccID.Text;
and have also tried:
rfv.ControlToValidate = rblCondition.ID;
lblAccID is a hidden text field used to store the ID of the row in the repeater.
Assign the control to validate property AFTER the ItemCreated event. I know this sounds weird, how would you still have the reference to the dynamically created control? I've gotten around this by keeping a reference to a List<Action> reference which I add things to during ItemCreated to be executed later.
In your control class you'll declare your List<Action> object:
List<Action> deferringControlToValidateUntilPreRender = new List<Action>();
Inside the ItemCreated event you'll have a line that looks like:
deferringControlToValidateUntilPreRender.Add(() => rfv.ControlToValidate = rblCondition.UniqueID);
And then, later, perhaps in PreRender:
foreach(var deferredAction in deferringControlToValidateUntilPreRender) action();
Since the RequiredFieldValidator is client-side code, you need to use the client id of the control. Like this:
rfv.ControlToValidate = rblCondition.ClientID;
Some more information from MSDN if you are interested:
Control.ClientIDMode Property
Also, an SO discussion on the differences between ClientID and UniqueID (as referenced in #MushinNoShin's answer, which, IMHO, is incorrect):
Why is there a difference between ClientID and UniqueID?

How to find the Controls in panel (which is added through literal)

Textbox1.text is user can enter html page name, so that its is appending to panel through literal.(loading html page to pannel).
string val = TextBox1.Text;
string location = Server.MapPath(".");
string path = location + "\\HTML\\" + val + ".html"; // HTML IS FOLDER NAME IN MY PROJECT
string readText = System.IO.File.ReadAllText(path);
Panel1.Controls.Clear();
Literal lit = new Literal();
lit.Text = readText;
Panel1.Controls.Add(lit);
Actually in Html page few controls which are in format of input (<input style="position: relative;" id="T0" onmouseup="mUp(this.id)" class="ui-draggable" onmousedown="mDown(this.id)" value="" type="text">)
I have to find those id's and text to save in database.
how to find the controls in panel now?
Give an ID to the control when you add it.
Literal lit = new Literal();
lit.Text = readText;
lit.ID = "myLiteral";
Panel1.Controls.Add(lit);
Then you can get it back as follows:
Literal lit = (Literal)Panel1.FincControl("myLiteral");
Remember that dynamically added controls must be created added again on every PostBack that follows as long as you want to have access to them.
Give your Literal an ID and then you can access it via FindControl...
Literal myLiteral = Panel1.FindControl("litId") as Literal;
if (myLiteral != null)
{
// ... do something
}
EDIT: (Missed the last part of your question)
You need to use ParseControl([string value]) on the HTML content which returns a control and then add that control (containing all child controls) to the Panel. Then you can use FindControl to locate child controls. For this method, the controls must be .NET controls (ie.
Since you did not give id to the control, u can find them by Panel1.Controls[index], since it is the first control added u can access at Panel1.Controls[0]

Categories

Resources