I have Dynamic CheckBoxList :
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ProjectOrigin.ascx.cs" Inherits="UserControl_PEM_ASPX_ProjectOrigin" %>
<div style="display:block;">
<asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatDirection="Horizontal" >
</asp:CheckBoxList></div>
and add ListItems in my function
private void ChkListBoxInit()
{
if (CheckBoxList1.Items.Count != 0) return;
CheckBoxList1.Items.Clear();
DesProvider p = new DesProvider();
List<tblDes> list = p.GetByDesGrpId(grpid).OrderBy(a => a.DesId).ToList();
ListItem li;
foreach (var l in list)
{
li = new ListItem(l.DesF, l.val);
CheckBoxList1.RepeatLayout = RepeatLayout.Flow;
CheckBoxList1.Items.Add(li);
}
}
The Html generated by this is:
<div style="display:block;">
<span id="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1">
<input id="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_0" type="checkbox" name="ctl00$MainContent$FormView1$ProjectOrigin1$CheckBoxList1$0" />
<label for="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_0">بهبود فرآیند کار</label>
<input id="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_1" type="checkbox" name="ctl00$MainContent$FormView1$ProjectOrigin1$CheckBoxList1$1" />
<label for="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_1">بهبود محیط کار</label>
<input id="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_2" type="checkbox" name="ctl00$MainContent$FormView1$ProjectOrigin1$CheckBoxList1$2" />
<label for="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_2">ایمنی و بهداشت</label>
<input id="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_3" type="checkbox" name="ctl00$MainContent$FormView1$ProjectOrigin1$CheckBoxList1$3" />
<label for="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_3">رفاهی</label>
<input id="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_4" type="checkbox" name="ctl00$MainContent$FormView1$ProjectOrigin1$CheckBoxList1$4" />
<label for="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_4">فروش و مشتریان</label>
<input id="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_5" type="checkbox" name="ctl00$MainContent$FormView1$ProjectOrigin1$CheckBoxList1$5" />
<label for="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_5">کاهش هزینه ها</label>
<input id="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_6" type="checkbox" name="ctl00$MainContent$FormView1$ProjectOrigin1$CheckBoxList1$6" />
<label for="ctl00_MainContent_FormView1_ProjectOrigin1_CheckBoxList1_6">سایر موارد</label>
</span>
</div>
How can i avoid ListItem text wrapping at end off line and keep checkbox and this text together?
Make sure that the <label> elements have the css setting display: block;. This should ensure that the label text all stays on the same line.
You can see this in this jfiddle. The example where the labels have display:inline; shows the same wrapping that you are seeing. The example where the labels have display:block; shows the text staying on the same line.
Update after html was posted in question:
Because the CheckBoxList is producing <input> separate from each related <label>, there is no easy way that I can see to keep them in flow, and guarantee that labels do not wrap and that labels and checkboxes stay on the same row. You could set label, input { float: right; display: block; } in your css, but this would allow labels to be on separate rows from their related inputs.
Best solution that I can see is to not use CheckBoxList. Instead, use a Repeater, with something like the following for layout:
<asp:Repeater id="checkboxes" runat="server">
<ItemTemplate>
<div class="checkboxItem">
<asp:CheckBox runat=server />
</div>
</ItemTemplate>
</asp:Repeater>
You would then data bind the repeater in a similar way, populating the value of CheckBox in each _ItemDataBound event.
Enclosing each CheckBox in a <div> and adding label, .checkboxItem { float: left; } in your css should force the checkboxes and labels to stay on the same line, per the technique showed in this answer.
Related
I would like to have the color of the 'CheckIn' button appear as green depending on the value of some other data in my code but I am unable to access that button outside of its onClick method. I should be able to access it via its ID but for some reason am unable to
<asp:ListView
ID="lvInstructors"
runat="server"
itemwDataBound="lvDataBound"
itemCommand="lvCommand"
Visible="true">
<LayoutTemplate>
<div class="container" id="mainContent">
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</div>
</LayoutTemplate>
<ItemTemplate>
<div class="row instructorItem" id="instructorItem">
<asp:HiddenField ID="sessionID" runat="server" Value='<%#Eval("SessionID")%>' />
<asp:HiddenField ID="hasChckedIn" runat="server" Value='<%#Eval("hasCheckedIn")%>' />
<div class="col-2 sessionStartTimeDiv">
<p class="sessionStartTime"><%#Eval("SessionStartTime")%></p>
</div>
<div class="col-2 instructorHeadshotDiv">
<asp:Image class="instructorHeadshot" runat="server" src='<%#Eval("InstructorHeadshot")%>' />
</div>
<div class="col-5 sessionInfoDiv">
<h3 class="instructorName"><%#Eval("InstructorName")%></h3>
<p class="sessionInfo"><%#Eval("SessionInfo")%></p>
</div>
<div class="col-3 checkInBtnDiv">
<asp:Button class="checkInBtn" ID="checkInBtn" runat="server" OnClick="CheckInBtn_Click" Text="Check-In"></asp:Button>
</div>
</div>
<hr />
</ItemTemplate>
<EmptyDataTemplate>
<br />
<br />
No Sessions to Display.
</EmptyDataTemplate>
</asp:ListView>
How I access it in onClick():
protected void CheckInBtn_Click(object sender, EventArgs e)
{
Button checkInBtn = (Button)sender;
checkInBtn.Text = "Check-Out";
checkInBtn.BackColor = Color.Green;
...
}
(Side Question: Why does SelectedIndex return -1 when I click that button ?)
In your itemwDataBound event, look for the value you need then set the button color there. Also you can set the value in the buttons command argument then grab it in the click event.
You need to Access your Button on ItemDataBound event of the ListView to change the color of the Button conditionally.
Here is the link which can help you with this:
datalist itemdatabound event having issues changing item bg color on condition
I am having an issue in getting the value of an input type = radio In c#
My form is in the master page as follows:
<form id="form1" runat="server">
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
<div class="header">
<asp:Label ID="DoctorName" runat="server" Text="" CssClass="Label"></asp:Label>
<asp:ImageButton ID="logout" ImageUrl="~/Logout.png" style ="float:right; margin-right:20px;" runat="server" Height="40" Width="30"/>
</div>
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
In my child page (c# file) I just tried to do the Request.form["MouvementYesNo"] but it returned a null value what should I do as another method ? should the two radio buttons have the same id? or how to get them by name?
<li>
<label>Troubles du mouvement <span class="required">*</span></label>
<input type="radio" runat="server" name="MouvementYesNo" value="Yes" checked> Yes
<input type="radio" runat="server" name="MouvementYesNo" value="No"> No
</li>
Since all of HTML radio buttons have runat="server" attribute which means they're accessible from code behind, put different control IDs and use if condition to check which radio button is selected.
Markup
<input id="RadioButton1" type="radio" runat="server" name="MouvementYesNo" value="Yes" checked> Yes
<input id="RadioButton2" type="radio" runat="server" name="MouvementYesNo" value="No"> No
Code behind
protected void Button1_Click(object sender, EventArgs e)
{
if (RadioButton1.Checked == true)
{
// do something
}
else if (RadioButton2.Checked == true)
{
// do something else
}
// other stuff
}
Note that if you want to use Request.Form, the HTML server control attribute (i.e. runat="server") should be removed, also Request.Form contains null value if no radio button input elements are selected.
Side note:
Better to use RadioButtonList server control like this:
<asp:RadioButtonList ID="MouvementYesNo" runat="server">
<asp:ListItem value="Yes">Yes</asp:ListItem>
<asp:ListItem value="No">No</asp:ListItem>
</asp:RadioButtonList>
And you can get currently selected radio button value later:
var selected = MouvementYesNo.SelectedValue;
Similar issue:
Getting value from html radio button - in aspx-c#
I had this error " Object reference not set .... " , I had checked my
code and I got that the error in UpdatePanel , when i removed it the
code worked well but I must use it to prevent all page reload .
<div>
<fieldset style="width: 498px; text-align: right; padding: 5px; direction: rtl;">
<legend>what do y think ? </legend>
<div class="add-post">
<textarea class="textarea" cols="3" rows="3" runat="server" id="txpost"></textarea>
<asp:RequiredFieldValidator ID="RVAddPost" runat="server" ForeColor="Red" ErrorMessage="*"
ControlToValidate="txpost" ValidationGroup="AddUserPost">*</asp:RequiredFieldValidator>
</div>
<asp:UpdatePanel ID="UPAddUserPost" runat="server">
<ContentTemplate>
<div class="add-post-control">
<div class="post">
<asp:Button Text="Submit" runat="server" ID="btAddPost" OnClick="btAddPost_Click" ValidationGroup="AddUserPost" />
</div>
<div class="fileUpload btn btn-primary">
<div class="fileUpload btn btn-primary">
<span>
<img src="res/images/img.png" width="38" height="27" /></span>
<input type="file" runat="server" class="upload" id="FUFile" />
</div>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btAddPost" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</fieldset>
<script type="text/javascript">
$('.textarea').focus(function () {
$(this).animate({
height: "80px"
}, 500);
$('.add-post-control').fadeIn(200);
});
</script>
</div>
Method:
protected void btAddPost_Click(object sender, EventArgs e)
{
AddpostfromFront();
}
private void AddpostfromFront()
{
if (FUFile.PostedFile.ContentLength != 0)
{
string tempVar = "~/res/Posts/" + FUFile.Value.ToString();
FUFile.PostedFile.SaveAs(Server.MapPath(tempVar));
ftier.Addpostfromfront(LoggedUserID, "4", txpost.Value, tempVar, DateTime.Now, DateTime.Now, false, false);
}
}
I think what you need to do instead of check the length of the file is to use a method that is built into PostedFile to check if there is a file to begin with.
if you look on the Microsoft page for PostedFile your code would look more like this
Private void AddpostfromFront() //I don't like your naming on this, should be AddPostFromFront
{
if (FUFile.HasFile)
{
string tempVar = "~/res/Posts/" + FUFile.Value.ToString();
FUFile.SaveAs(tempVar);
}
}
to use these methods you may have to use the ASP control instead of the HTML tag, <asp:FileUpload></asp:FileUpload> you will have to adjust the attributes to fit your situation and naming scheme. This would replace your HTML tag <input type="file" runat="server" class="upload" id="FUFile" />
I think that you are meshing two processes into one and getting confused as to what your code should be doing.
no clue what ftier is and why it has the same method name with the same bad naming scheme, or what it is doing with that information.
you should do this in 3 steps
upload the file
save the file
if you need to display the file then do so with the file that is saved, not the file that is being uploaded.
When using the RadioButtonList control, I can access the selected value in my codebehind with the following:
rbMyButtons.SelectedValue
However, I'd like to use HtmlInputRadioButton controls instead as these give me greater control over the rendered markup. If I'm using a list of <input type="radio" runat="server" /> then, as far as I know, I have to do something like this:
if (rbMyButtonsOption1.Checked)
{
...
}
else if (rbMyButtonsOption2.Checked)
{
...
}
else if ...
Is there a way I can mimic the behaviour of RadioButtonList.SelectedValue without using Request.Form["name"]?
Here's how I would do it:
First, wrap the Html Controls inside a panel or similar grouping object (the panel will be rendered as a div):
<asp:Panel runat="server" ID="ButtonList" ClientIDMode="Static">
<input type="radio" name="seasons" value="Spring" runat="server" />Spring <br/>
<input type="radio" name="seasons" value="Summer" runat="server" /> Summer <br/>
<input type="radio" name="seasons" value="Fall" runat="server" /> Fall <br/>
<input type="radio" name="seasons" value="Winter" runat="server" /> Winter <br/>
</asp:Panel>
Then, create an extension method to access the ControlCollection property of the panel and iterate through the collection:
public static class HelperFunctions
{
public static string GetRadioButtonValue(this ControlCollection collection)
{
foreach (var control in collection)
{
if (control is HtmlInputRadioButton)
{
var radioControl = ((HtmlInputRadioButton)control);
if (radioControl.Checked)
{
return radioControl.Value;
}
}
}
//If no item has been clicked or no Input Radio controls are present we return an empty string
return String.Empty;
}
}
Finally you can get the value with ease:
var selectedValue = ButtonList.Controls.GetRadioButtonValue();
I did some searching to find this, so thought it may be useful even though the question is over 1 year old...
I've just come across this issue. I needed to use use [input type="radio" runat="server" ...] as I had to include additional HTML "data-*" attributes against each selection.
I've used a composite of the two answers here to come with a solution that helped me.
My HTML looks like:
<div id="pnlOpts" runat="server">
<input type="radio" name="rblReason" runat="server" value="1" /> <label>Opt 1</label><br />
<input type="radio" name="rblReason" runat="server" value="3" data-att="1" /> <label>Supplied Reason 1 </label><br />
<input type="radio" name="rblReason" runat="server" value="3" data-att="2" /> <label>Supplied Reason 2 </label><br />
<input type="radio" name="rblReason" runat="server" value="3" data-att="3" /> <label>Supplied Reason 3 </label><br />
</div>
My Code-behind looks like:
if(pnlOpts.Controls.OfType<HtmlInputRadioButton>().Any(a=>a.Checked))
{
HtmlInputRadioButton selected = pnlOpts.Controls.OfType<HtmlInputRadioButton>().Where(a => a.Checked).FirstOrDefault();
var btnValue = selected.Value;
var dataAttVal = selected.Attributes["data-att"];
...
}
You can mimic this behavior using LINQ:
var radioButtons = new[] { rbMyButtonsOption1, rbMyButtonsOption2 };
var checkedRadioButton = radioButtons.FirstOrDefault(i => i.Checked);
if (checkedRadioButton != null)
{
// do something...
}
I have an ASP.NET usercontrol that implements the ValidationProperty attribute. This attribute successfully makes it possible for me to use a RequiredFieldValidator for my custom control, however on validation it causes a full postback rather than using client side javascript based validation.
Is there a way to prevent this and enable client side validation without using a custom validator?
This is the what my UserControl looks like.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ucBooleanRadio.ascx.cs" Inherits="MyCompany.Web.UserControls.ucBooleanRadio" %>
<div class="BooleanRadio">
<input runat="server" id="radTrue" type="radio" name="BooleanRadio" value="True" /> Yes
<input runat="server" id="radFalse" type="radio" name="BooleanRadio" value="False" /> No
</div>
[ValidationProperty("Checked")]
public partial class ucBooleanRadio : System.Web.UI.UserControl
{
public Nullable<bool> Checked
{
get
{
if (radTrue.Checked || radFalse.Checked)
return radTrue.Checked;
else
return null;
}
set
{
radTrue.Checked = value != null ? value.Value : false;
radFalse.Checked = value != null ? !value.Value : false;
}
}
}
And this is how it is being used
<uc1:ucBooleanRadio ID="ucAgree" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" CssClass="Validator" Display="Dynamic" ControlToValidate="ucAgree" InitialValue="" ErrorMessage="You must agree to continue."></asp:RequiredFieldValidator>
Page.Validate();
if (Page.IsValid)
{
//Do stuff
}
Turns out, ASP.NET don't event care about element tag.
I've just looked through validation code and found this
function ValidatorGetValue(id) {
var control;
control = document.getElementById(id);
if (typeof(control.value) == "string") {
return control.value;
}
return ValidatorGetValueRecursive(control);
}
So
<div class="BooleanRadio" id="<%= ClientID %>" value="<%= radTrue.Checked? "true" : radFalse.Checked? "false" : "" %>">
<% radTrue.Attributes["onclick"] = "document.getElementById('" + ClientID + "').value='true'"; %>
<% radFalse.Attributes["onclick"] = "document.getElementById('" + ClientID + "').value='false'"; %>
<input runat="server" id="radTrue" type="radio" name="BooleanRadio" value="True" /> Yes
<input runat="server" id="radFalse" type="radio" name="BooleanRadio" value="False" /> No
</div>
actually works :\, as does
<div class="BooleanRadio" id="<%= ClientID %>">
<input runat="server" id="radTrue" type="radio" name="BooleanRadio" value="True" /> Yes
<input runat="server" id="radFalse" type="radio" name="BooleanRadio" value="False" /> No
</div>
And there is events autohooking - validated element (one with ClientID) and its children are wired to cause validation automatically (look ValidatorHookupControl).
That may result in:
1. user does something
2. validation is performed
3. value to validate is updated (after validation!)
First example with value on div behaves this way.
For a simple client-side validation there should be an input element with corresponding name which value is to be validated. Example of how it could be done in your case:
<div class="BooleanRadio">
<% radTrue.Attributes["onclick"] = "document.getElementsByName('" + UniqueID + "')[0].value='+'"; %>
<input runat="server" id="radTrue" type="radio" name="BooleanRadio" value="True" /> Yes
<% radFalse.Attributes["onclick"] = "document.getElementsByName('" + UniqueID + "')[0].value='-'"; %>
<input runat="server" id="radFalse" type="radio" name="BooleanRadio" value="False" /> No
<input name="<%= UniqueID %>" type="hidden" value="<%= radTrue.Checked? "+" : radFalse.Checked? "-" : "" %>" />
</div>
OK, So after significant digging around in the architecture of the ASP.NET field validators and some guidance from the poster above I have finally found the solution.
Basically the answer above is correct barring a couple of changes.
Firstly the id that is set for the hidden text should not be in the Name field but rather the ID field. Further the ID that is populated inside of the Hidden field should not be the Page.UniqueID but rather the Page.ClientID for the UserControl in question.
The reason for this is that when a page that contains validators is loaded the following function is called by the ASP.NET framework.
function ValidatorHookupControlID(controlID, val) {
if (typeof (controlID) != "string") {
return;
}
var ctrl = document.getElementById(controlID); //NOTE THIS LINE
if ((typeof (ctrl) != "undefined") && (ctrl != null)) {
ValidatorHookupControl(ctrl, val);
}
else {
val.isvalid = true;
val.enabled = false;
}
}
What the framework attempts to do is retrieve a control that has the same ID as the ControlToValidate property as set in the required field validator (which is actually Page.ClientID). It then uses this control in its validation functions (whether they be RequiredField, Compare, Regex and so on). If it finds such a control it enables the validator and performs validation against its value, if it doesn't it simply sets the validator to disabled.
In the end my code looks like this.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ucBooleanRadio.ascx.cs" Inherits="MyCompany.Web.UserControls.ucBooleanRadio" %>
<input id="<% =this.ClientID %>" type="hidden" value="" />
<asp:RadioButton runat="server" ID="radTrue" Text="Yes" GroupName="radio" />
<asp:RadioButton runat="server" ID="radFalse" Text="No" GroupName="radio" />
<script language="javascript" type="text/javascript">
$(function (e) {
$("#<% =radTrue.ClientID %>").click(function (e) {
$("#<% =this.ClientID %>").val("true");
});
$("#<% =radFalse.ClientID %>").click(function (e) {
$("#<% =this.ClientID %>").val("false");
});
});
</script>
And the code behind remains unchanged. Hopefully this explains some of the mystery of whats going on to anyone who runs into the same problem.
Maxim, I've just been working on a similar problem.
I've found that you don't need the JavaScript the Validators will automatically iterate through the controls looking for a "value" that is set.
You must be using server side RadioButtons rather than HTML
If you're using CompositeControls then it will work automatically
If you're using Web User Controls (ascx files) it doesn't wrap the control with an ID so you need to add the following code to your control.
<div id='<%=ClientID %>'>
Your radio button controls here...
</div>
Edit: I've just uploaded some quick sample code. Hope this helps!
Sample Code