Dynamicaly Customize the UI of a User Control - c#

I want to change the position of elements in ASP.NET User Control UI dynamically based on a condition. For eg:-
Here is the Normal layout of my User Control
Now I want to re position the Edit button as below based on a condition.
I can think of following approaches but not sure if they are good and best way to do this.
We can create a Button in the desired place of my user control and then Show that button based on this condition and hide the original button. So the user control will have Two buttons in the UI (one Inline and other in a new line). Based on my condition, I show or hide them respectively.
Create another User Control and use it.
But I guess for this small change its kind of overkill
Are there any best known methods/better solution out there to handle such kind than what I can think of
Any constructive input would help.

You can create two buttons, one button in the desired place of my user control and one in the target place. The first button will be displayed as block by default and the second button will be displayed as none by default. Depend on your condition you can change the class of the first button and second button to make the first one hidden and the second will be displayed as block. Here is an example :
In source :
<style>
.HideButton {
display: none;
}
.ShowButton {
display: block;
}
</style>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" />
</td>
</tr>
<tr>
<td>
<asp:Button CssClass="HideButton" ID="Button2" runat="server" Text="Button />
</td>
<td"> </td>
</tr>
</table>
</div>
</form>
In code behind :
if (something)
{
Button1.CssClass = "HideButton";
Button2.CssClass = "ShowButton";
}
Another solution is to change the innerHTML of td tag as follow :
In source :
<form id="form1" runat="server">
<div>
<table>
<tr>
<td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
<td id="DesiredLocation" runat="server"><input type="button" value="button1" /></td>
</tr>
<tr>
<td id="TargetLocation" runat="server"></td>
<td"></td>
</tr>
</table>
</div>
</form>
And in aspx code :
if (something)
{
TargetLocation.InnerHtml = DesiredLocation.InnerHtml;
DesiredLocation.InnerHtml = "";
}
Hope this work.

Related

Control 'txtUserName' of type 'TextBox' must be placed inside a form tag with runat=server

I have this error - Control 'txtUserName' of type 'TextBox' must be placed inside a form tag with runat=server. I am unable to get rid of it, my text box is placed inside a form tag with runat=server.
The page which I am getting this on is my 'reset password' page I want the users to be able to enter their username and once they press the reset password button it takes them to a page which allows them to change their password.
Here is the code that I am currently working with.
<head runat="server">
<title></title>
</head>
<body>
<div style="font-family:Arial">
<table style="border: 1px solid black; width:300px">
<tr>
<td colspan="2">
<b>Reset my password</b>
</td>
</tr>
<tr>
<td>
User Name
</td>
<td>
<form action="ChangePassword.aspx" method="get">
<asp:TextBox ID="txtUserName" Width="150px" runat="server"
ontextchanged="txtUserName_TextChanged">
</asp:TextBox>
</form>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnResetPassword" runat="server"
Width="150px" Text="Reset Password" onclick="btnResetPassword_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
</table>
</div>
</body>
</html>
As the error message says, you need to add a runat="server" in the form tag. This is just something ASP.NET demands to work.
The way ASP.NET handles events and postbacks forces this requirement. It tries to keep the page's state inside the actual page (called the 'view state'), and on form submission it sends it back. This was invented to make the stateless web stateful.
Just put in the runat="server" inside the form tag and you will be set.
<form runat="server" action="ChangePassword.aspx" method="get">
Add < form> tag like this...,
it will work..

How to create a RadioButtonList where each radio button is in a separate table row?

I'm creating an MCQ Question and answer Interface where I need to place my each radio option in separete row next to the answer, so that user can select the answer, I know to use radiobutton list in a single row in normal way,
<asp:RadioButtonList ID="opt_questiontype" runat="server" RepeatLayout="Flow" OnClick="call()">
<asp:ListItem Value="MCQ" Selected="True">MCQ</asp:ListItem>
<asp:ListItem Value="Single">Single Answer</asp:ListItem>
</asp:RadioButtonList>
but here i need to place them in row by row in an html table as follows,
<table id="mcqtable">
<tr style="border-bottom-style:solid; border-bottom-width:1px; border-bottom-color:#CCCCCC;">
<th class="captions2">Option</th><th class="captions2">Answer Text</th><th class="captions2">Is Correct</th>
</tr>
<tr>
<td class="captions1">Answer Option 1</td><td><asp:TextBox ID="txt_answeropt1" runat="server" TextMode="SingleLine" Width="600px"></asp:TextBox></td><td><asp:RadioButton ID="opt_answer1" runat="server" GroupName="grp_answers" Checked="true" /></td>
</tr>
<tr>
<td class="captions1">Answer Option 2</td><td><asp:TextBox ID="txt_answeropt2" runat="server" TextMode="SingleLine" Width="600px"></asp:TextBox></td><td><asp:RadioButton ID="opt_answer2" runat="server" GroupName="grp_answers" /></td>
</tr>
<tr>
<td class="captions1">Answer Option 3</td><td><asp:TextBox ID="txt_answeropt3" runat="server" TextMode="SingleLine" Width="600px"></asp:TextBox></td><td><asp:RadioButton ID="opt_answer3" runat="server" GroupName="grp_answers" /></td>
</tr>
<tr>
<td class="captions1">Answer Option 4</td><td><asp:TextBox ID="txt_answeropt4" runat="server" TextMode="SingleLine" Width="600px"></asp:TextBox></td><td><asp:RadioButton ID="opt_answer4" runat="server" GroupName="grp_answers" /></td>
</tr>
</table>
Here I have used normal radiobuttons, but there is a conflict when getting the selected value, So please any one could suggest a way to use asp:RadioButtonList to do this task?
here I have used normal radiobuttons, but there is a conflict when
getting the selected value
What is conflict? why you want to use RAdioButtonList here? Your existing code does not show me any conflict.
Either use repeater or you can use css to create single row for each radio button.
In repeater you can control the HTML as per your requirement
You should set RepeatDirection="Vertical" in order to show the options row-wise.
Please refer my answer #CodeProject - Change ASP radiobuttonlist repeatdirection property with Javascript or JQuery for a more detailed information on how we can toggle between Vertical and Horizontal alignments.
Demo - [Demo] Change Repeat Direction of asp RadioButtonList
EDIT
Do like below...
<asp:RadioButtonList ID="opt_questiontype" runat="server" RepeatLayout="Flow" RepeatDirection="Vertical" OnClick="call()">

How do I create new controls inserted into newly generated HTML on runtime?

I am still rather new to ASP.NET, but I find myself stuck on a problem that shouldn't be too much of a problem..
Right now I have a page that holds this div:
<div id="EditSurveySetID" class="EditSurveySet" runat="server">
<div class="cell">
<div class="cell_title">Survey Set(s)</div>
<table id="surveySetTableData" runat="server" style="margin: 10px;">
<tbody>
<tr>
<td class="form_labelSurveySet" style="width: 330px;">
<input type="button" value="-"> Survey Set 1:
<input id="EditSurveySetTitle" runat="server" style="width: 200px;" value="Netherlands">
</td>
<td>
<asp:DropDownList ID="DDLSurveySetSurveys" runat="server">
</asp:DropDownList>
<asp:Button ID="addAdditionalDDLColumns" runat="server" Text="+" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
Which looks like this:
I want a user to press the + button (addAdditionalDDLColumns). Upon pressing that button, I want a new table row to appear with the same controls in it, so that on runtime, it would look like this at that point:
<div id="EditSurveySetID" class="EditSurveySet" runat="server">
<div class="cell">
<div class="cell_title">Survey Set(s)</div>
<table id="surveySetTableData" runat="server" style="margin: 10px;">
<tbody>
<tr>
<td class="form_labelSurveySet" style="width: 330px;">
<input type="button" value="-"> Survey Set 1:
<input id="EditSurveySetTitle" runat="server" style="width: 200px;" value="Netherlands">
</td>
<td>
<asp:DropDownList ID="DDLSurveySetSurveys" runat="server">
</asp:DropDownList>
<asp:Button ID="addAdditionalDDLColumns" runat="server" Text="+" />
</td>
</tr>
<tr>
<td class="form_labelSurveySet" style="width: 330px;">
<input type="button" value="-"> Survey Set 2:
<input id="Text1" runat="server" style="width: 200px;" value="Netherlands">
</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="+" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
Or in image:
So the way I see, some new HTML code is generated on the + button click event, along with some controls (dropdownlist, another + button with the same functionality(?), possibly a textfield instead of input field).
Questions that come to mind right now:
How do I generate the HTML code that would create a new table row
How do I control where this generated HTML code is added (in this case, it should be under the existing
[Vague/Abstract question] Ultimately a user could possibly have 1 to infinite 'survey sets'. If a user were to have created 4 survey sets, he would eventually press a save button or something alike. Upon pressing this button I would save the 4 selectedvalues of the 4 dropdownlists belonging to the 4 survey sets. How would I call each individual dropdownlist in order to get the data? What I'm actually asking, I think, is whether it's possible to assign an ID programmatically upon the auto generated dropdownlist creation of my previous two questions.
How do I do this? Any advise and tips are very welcome!!
You could use and UpdatePanel and dynamically add new asp controls in the code-behind.
This could be expensive however, because it means your application would be going back to the server every time the user clicks the "Add" button, however I'm not sure how you'd achieve this strictly on the client-side. But there is nothing stopping you creating new controls on the fly on the server-side using asp.net.
If you want to surround the new controls with custom HTML, you could use a PlaceHolder component and replace it with raw text (your HTML) during the callback.
I would suggest you use a GridView.
It provides an option to add rows. It provides a Rows collections, so you can get the data bound to each row.
Here are some examples to get you started.
Dynamically creating, adding and maintaining controls would involve some effort. You would need a PlaceHolder and have to add controls to that. You would have to assign unique ids to each one of them, and use those to retrive the values. This must be done on each PostBack.
Try this when you don't feel you are rather new to asp.net.
protected void Button1_Click(object sender, EventArgs e)
{
HtmlTableRow tr = new HtmlTableRow();
HtmlTableCell td = new HtmlTableCell();
Button btn=new Button();
btn.Text="gdfgd"; /* here u can create ur contol and add it in cell*/
td.Controls.Add(btn); /*add controls to colum*/
tr.Cells.Add(td); /*add column to row*/
surveySetTableData.Rows.Add(tr); /*ad row to table*/
}
instead of using this i would also recommend u to use gridview like nunespaqscal bcz dataretrival become very easy....in gridview

Object Required Error from Javascript

In my aspx page, I have two radio buttons and a table.. if one of the radio buttons is checked it should make the table visible if the other one is checked invisible.. but this line is giving me a "JS Object Required". I am firing this from code behind .cs.. it fires fine but then i get that error.
document.getElementById('tblnewpackinglogo').style.display = '';
See code below
JAVASCRIPT
<script language="javascript" type="text/javascript">
function ShowImage() {
var rdoImg = document.getElementById("<%=radImage.ClientID%>");
if (rdoCurrImage2.checked == true) {
document.getElementById('tblnewpackinglogo').style.display = 'none';
}
else {
document.getElementById('tblnewpackinglogo').style.display = '';
}
}
</script>
TABLES
<table id="tblImage" border="0" cellpadding="0" cellspacing="10" runat="server"
visible="true">
<tr>
<td>
<asp:Image ID="imgLogo" runat="server" />
</td>
<td>
<div class="FieldStyle">
Select an Option</div>
<asp:RadioButton ID="radImage"
Text="Keep Current Image"
runat="server"
GroupName="LogoImage"
OnCheckedChanged="radImage_CheckedChanged"
Checked="True" />
<asp:RadioButton ID="radNewImage"
Text="Upload New Image" runat="server"
GroupName="LogoImage"
OnCheckedChanged="radNewImage_CheckedChanged" />
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
<table id="tblnewpackinglogo" border="0" cellpadding="0" cellspacing="0" width="100%"
runat="server" style="display:none;">
<tr>
<td style="height: 41px">
<div class="Style">
Select a Logo Image</div>
<div class="ValueStyle">
<asp:FileUpload ID="UploadImage"
runat="server"
Width="300px" />
</div>
</td>
</tr>
</table>
It's probably that you need to get the name-mangled ClientID of the table:
document.getElementById('<%= tblnewpackinglogo.ClientID %>').style.display = '';
You're already doing it with the radio button above.
Also, if you're injecting the script from the code-behind file, then you'll still need to use the ClientID, as the JavaScript will run on client-side.
That error means that something of the form (null or undefined expression).someproperty is occurring. Naturally there is no someproperty on null/undefined. For the line:
document.getElementById('tblnewpackinglogo').style.display = '';
It is most likely that the problem is getElementById is returning undefined which would be caused if there was no element with the id tblnewpackinglogo at the time it was invoked.
Since there is a tblnewpackinglogo then -- unless FishBasketGordo's answer is correct -- I suspect the issue may be that ShowImage is invoked before the DOM has been loaded. Either that or there is another trivial error that does not align with the above post.
Inspect the actual HTML to see what is generated and use a tool like FireBug to try getElementById manually. Both FireBug and MS Script Debugger also offer more detailed debugging support to inspect the state at the time of the exception.
Happy coding.

asp.net custom control with form field validation issue

I have created a custom asp .net control some fields have validation controal associated with them.
The problem arised when I declare more than one initialization on a page. When I hit submit on one of the intialized control, form validation occur on all other control that were declared. Due to this issue I cannot submit a form. Here is the code
<%# Control Language="C#" AutoEventWireup="true" CodeFile="FinancialAdvisorHelp.ascx.cs" Inherits="FinancialAdvisorHelp" %>
<table width="316" border="0" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2" >
<asp:RequiredFieldValidator
ID="RequiredFieldValidatorMember" runat="server"
ErrorMessage="Pleae enter member name. " ControlToValidate="TextBox_Name"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail" runat="server" ErrorMessage="Please enter email. " ControlToValidate="TextBox_email"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorDarryEmail" runat="server"
ControlToValidate="TextBox_email" ValidationExpression=".*#.*\..*"
ErrorMessage="<br>
Invalid Email."> </asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td width="165"><p style="font-family:Palatino Linotype; font-size:12px; margin:0; padding:0;">Member Name*</p>
<asp:TextBox ID="TextBox_Name" runat="server" CausesValidation="True"></asp:TextBox>
</td>
<td width="151" align="right"><p style="font-family:Palatino Linotype; font-size:12px; margin:0 0 0 4px; padding:0; text-align:left;">E-Mail Address*</p>
<asp:TextBox id="TextBox_email" runat="server" CausesValidation="True"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="right"><p style="font-family:Palatino Linotype; font-size:12px; margin:0; padding-right:50px;"><br />
Telephone Number</p>
<asp:TextBox id="TextBox_phone" runat="server" CausesValidation="True"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2"><p style="font-family:Palatino Linotype; font-size:12px; margin:0; padding:0;">Ask Darryl your question</p>
<asp:TextBox ID="TextBox_question" runat="server" Rows="7" Columns="48"
style="width:310px" TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2"><p style="font-size:10px; margin:0; padding:0; float:left; width:240px; line-height:12px;">Note: you should receive a response within two (2) business days.<br />
*Required information.</p>
<asp:ImageButton ID="ImageButton_Advisor" runat="server" alt="submit"
width="63" height="18"
style="border:0; padding:0; margin:10px 0 0 0; float:right;" ImageUrl="./images/investments/submit.gif"
/>
<asp:HiddenField ID="HiddenFieldAdvisorEmail" Value="" runat="server" />
</td>
<tr><td colspan="2">
</td></tr>
</tr>
</table>
Use the ValidationGroup attribute on all form elements that cause validation including the submit button. When validation is triggered, it will only check other elements with the same ValidationGroup specified.
To make sure it is unique across each instance of your control on the page use your UserControl's ID as the validation group in the code behind.
RequiredFieldValidatorEmail.ValidationGroup = this.ClientID;
More information can be found here: http://www.dotnet-guide.com/validationgroups.html
I'm having a hard time deciphering your question.
Validation Groups
It sounds like you might want to take advantage of validation groups . When you have multiple triggers that should validate different controls, this is what to use.
Check your Validators and Custom Controls
If you are still having issues, when validators have errors and you trigger validation, it appears that "nothing happens" (what really is happening is that the validators error out and the page kind of just stops). It can also be possible that your custom controls have issues.
Check your Validators and ID's
The problem arised when I declare more
than one initialization on a page
What do you mean by this? I wonder if you are declaring controls dynamically in your code? This could also be your problem. Each ASP.NET control (including validators, custom controls, ... ) needs it's own unique ID. You can also have more than one validator checking a single control, but a single validator can't validate multiple controls.

Categories