ASPxComboBox - How to set selected item? - asp.net

I'm using : ASPxComboBox
The problem is how to set selectedValue from code behind? If my html is like this:
<dxe:ASPxComboBox ID="cbxJobType" runat="server" width="200px" MaxLength="50">
<Items>
<dxe:ListEditItem Text="Contract" Value="0" />
<dxe:ListEditItem Text="Full Time" Value="1" />
<dxe:ListEditItem Text="Part Time" Value="2" />
</Items>
<ValidationSettings ErrorDisplayMode="ImageWithTooltip">
<RequiredField ErrorText="Required Value" IsRequired="True" />
</ValidationSettings>
</dxe:ASPxComboBox>

Client-Side Script
Give ClientInstanceName property to comboBoxto access it client side and ID property as cbxJobType to access control server side.
// by text
comboBox.SetText('Text #2');
// by value
comboBox.SetValue('Value #2');
// by index
comboBox.SetSelectedIndex(1);
Server-Side Code
// by text
cbxJobType.Text = "Text #2";
// by value
cbxJobType.Value = "Value #2";
// by index
cbxJobType.SelectedIndex = 1;
This code works fine too:
cbxJobType.SelectedItem = cbxJobType.Items.FindByValue("Value #2");

You can either:
Set the ASPxComboBox.SelectedIndex property;
Select the required Item by its Value via the ASPxComboBox.Value property:
Code Behind:
cbxJobType.SelectedIndex = 0;
//or
cbxJobType.Value = "0";

On the client side, I found there is the equivalent of Ruchi's suggestion:
cbxJobType.SelectedItem = cbxJobType.Items.FindByValue("Value #2");
Which is:
cbxJobType.SetSelectedItem(cbxJobType.FindItemByValue("Value #2"));
// or
cbxJobType.SetSelectedItem(cbxJobType.FindItemByText("Text #2"));
Go here to learn more about the ASPxComboBox on the client side (ASPxClientComboBox).
Go here to learn more about the ASPxComboBox on the server side.
There you can browse through all their members, constructors, events and methods.

You can also look at the following
cbxJobType.SelectedIndex = cbxJobType.Items.IndexOf(cbxJobType.Items.FindByValue("Value"));
Hope though this is posted late, it may help someone else

Related

asp:ListBox SelectedValue not setting (dynamically or when clicked)

I have an asp:ListBox that is populated dynamically from js based on the selected value of another asp:List box. The problem is that the second list box always returns a SelectedValue of "" regardless of whether i set lstBox.selectedIndex = 0 or actually select an item in the list.
.js to add to list then set default selected item
var Option = document.createElement("option");
lstId = document.getElementById(lstId);
Option.text = lstItem;
lstId.add(Option);
lstId.selectedIndex = 0;
.vb to get selected value
Dim selSchedule As String = lstCRMSched.SelectedValue
Now as this list is populated by javascript i had to set my #page EnableEventValidation = "false" otherwise the postback that came later would fail.
Side note: I'm noticing that asp.net doesn't like it when you use hidden divs as overlays that are unhidden based on menu selections as everything it does requires a postback, which wipes out the state of the other divs. Should i just have 10 .aspx files one for each div and just switch locations from the codebehind using sessions to transfer things like selected values and data that is to be shown in another div?
You can access the SelectedValue of the drop down list through the Request object since every element in the form that has a name is submitted in the request.
You simply need to do this:
Dim selSchedule As String = Request[lstCRMSched.UniqueID]
Now, this will work just because you disabled EventValidation on the page. The error you were getting is completely normal. ASP.NET is just making sure that no one sends data that wasn't rendered by the server initially to prevent attacks. If you were to keep the EventValidation enabled on the page, you'd need to register the list for Validation via ClientScriptManager.RegisterForEventValidation
If you add items to the dropdownlist on the client these items are not persisted on the server!
But you may try saving dynamically added items (text-value-pairs) within some hidden input fields and parse them out on the server. See this link for a working example. For your example you will also have to save your selectedIndex within another hidden field to be able to access it on the server.
EDIT
demo.aspx
<script type="text/javascript">
function saveValue() {
var hiddenField1 = document.getElementById("hiddenField1");
hiddenField1.value = "hello world";
}
</script>
<form id="Form1" method="post" runat="server">
<input type="hidden" id="hiddenField1" name="hiddenField1" value="" />
<asp:Button ID="btnPostBack" runat="server" Text="PostBack"
OnClientClick="saveValue()" onclick="btnPostBack_Click" />
</form>
demo.aspx.cs
protected void btnPostBack_Click(object sender, EventArgs e)
{
Debug.WriteLine("Value of hiddenField1: " + Request["hiddenField1"]);
Debugger.Break();
}
This one worked for me. I got "hello world" on the server.
EDIT 2
Icarus pointed out that you can always access any submitted element to the server by referring to the Request object and of course he is absolutelly right! According to your question I thought you'd like to have access to all dynamically created items - and that is - with solution shown below - not possible.
aspxPage
<script type="text/javascript">
function saveToList() {
var ListBox1 = document.getElementById("ListBox1");
var ListBox2 = document.getElementById("ListBox2");
var Option = document.createElement("option");
Option.text = ListBox1.options[ListBox1.selectedIndex].text;
ListBox2.add(Option);
ListBox2.selectedIndex = 0;
}
</script>
<form id="Form1" method="post" runat="server">
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem Text="entry1" Value="1" />
<asp:ListItem Text="entry2" Value="2" />
<asp:ListItem Text="entry3" Value="3" />
<asp:ListItem Text="entry4" Value="4" />
</asp:ListBox>
<asp:ListBox ID="ListBox2" runat="server" Width="100"></asp:ListBox>
<input id="Button1" type="button" value="Save to List" onclick="saveToList()" />
<asp:Button ID="btnPostBack" runat="server" Text="PostBack" OnClick="btnPostBack_Click" />
codeBehind
protected void btnPostBack_Click(object sender, EventArgs e)
{
Debug.WriteLine("SelectedValue of ListBox2: " + Request["ListBox2"]);
// no access to all other clientSide created items in ListBox2
Debugger.Break();
}

Check if value of textbox extended with MaskedEditExtender is valid?

Below is my code:
<asp:TextBox
ID="FromDateTextBox"
runat="server" />
<asp:ImageButton
ID="FromDateImageButton"
runat="server"
ImageUrl="~/images/calander.png" />
<ajaxkit:CalendarExtender
ID="FromDate"
runat="server"
TargetControlID="FromDateTextBox"
CssClass="CalanderControl"
PopupButtonID="FromDateImageButton"
Enabled="True" />
<ajaxkit:MaskedEditExtender
id="FromDateMaskedEditExtender"
runat="server"
targetcontrolid="FromDateTextBox"
Mask="99/99/9999"
messagevalidatortip="true"
onfocuscssclass="MaskedEditFocus"
oninvalidcssclass="MaskedEditError"
masktype="Date"
displaymoney="Left"
acceptnegative="Left"
errortooltipenabled="True" />
<ajaxkit:MaskedEditValidator
id="FromDateMaskedEditValidator"
runat="server"
controlextender="FromDateMaskedEditExtender"
controltovalidate="FromDateTextBox"
emptyvaluemessage="Date is required"
invalidvaluemessage="Date is invalid"
display="Dynamic"
tooltipmessage="Input a date"
emptyvalueblurredtext="*"
invalidvalueblurredmessage="*"
validationgroup="MKE" />
I've set Culture="auto" UICulture="auto" in #Page directive and EnableScriptGlobalization="true" EnableScriptLocalization="true" in script manager to have client culture specific date format in my textbox.
I also have a Go button on my page on which I will do a partial post back. So, I want to validate the FromDateTextBox in javascript when the Go button is clicked.
UPDATE
I know how to create a javascript click handler. But because masked editor is already validating the date on focus shift, I'm thinking there should be some boolean property (like IsValid) exposed by it which will allow me to see if the text box contains valid date.
FURTHER TRIALS
I also tried below code and Page_Validators[f].isvalid always returns true even when the date is invalid and MaskEditValidator shows me a red star near the Text box.
function isDateValid() {
var b = true;
for (var f = 0; f < Page_Validators.length; f++) {
if (!Page_Validators[f].isvalid)
b = false;
}
return b;
}
$('#GoButton').click(function() {
if (!isDateValid()) {
return false;
}
loadProducts();
});
Sorry do you mean that your MaskedEditValidator is not working when clicking GO button? Or if you want to write some js to check the date yourself? In this case you can add a client onclick event to GO button. One example in code behind is:
goButton.Attributes["onclick"] = "if (!CheckDate()) return false;";
And in the page file add a javascript function:
function CheckDate()
{
//check the date here
return isValid;
}
Now if the date is not valid,the CheckDate() will return false, the goButton event will also return without posting back.
I resolved it. Basically when there is an invalid date entered in the textbox the MaskedEditExtender changes the provided (OnInvalidCssClass="MaskedEditError") class of the textbox and I picked it up as a checking point for validation.
$('#GoButton').click(function () {
if($('#<%=FromDateTextBox.ClientID%>').hasClass('MaskedEditError')) {
return false;
}
}

Telerik RadComboBox javascript API problem

I've been having a problem using the javascript API of the RadComboBox from Telerik. And no I don't have the power to switch over from Telerik to jQuery or another framework.. Suffice to say I have hardly any hair left on my head now :P
In a nutshell I want to grab the selected index of one RadComboBox, and update another RadComboBox to this index. Eg. selecting a value in the first RCB automatically updates the second on the client side. My problem really is that I can't find a way to set the index on the second RCB, even though the docs says there is an easy way to do it .. (you heard that one before right :)
I've followed the API docs at this page (telerik docs), and also used the javascript debugger in IE8 and the excellent FireBug in Firefox. I'm using Telerik.Web.UI assembly version 2009.2.826.20
I don't need full source for a solution, but a nudge in the right direction would be much appreciated! :)
Here's some example code I cooked together:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<script type="text/javascript" language="javascript">
function masterChanged(item)
{
var detailCB = <%= DetailCB.ClientID %>;
var index = item.get_selectedIndex();
detailCB.SetSelected(index); //method does not exist, but should according to the docs..
}
</script>
<div>
<telerik:RadComboBox ID="MasterCB" runat="server" OnClientSelectedIndexChanged="masterChanged">
<Items>
<telerik:RadComboBoxItem Text="One" Value="1" runat="server" />
<telerik:RadComboBoxItem Text="Two" Value="2" runat="server" />
<telerik:RadComboBoxItem Text="Three" Value="3" runat="server" />
</Items>
</telerik:RadComboBox>
</div>
<div>
<telerik:RadComboBox ID="DetailCB" runat="server">
<Items>
<telerik:RadComboBoxItem Text="One" Value="1" runat="server" />
<telerik:RadComboBoxItem Text="Two" Value="2" runat="server" />
<telerik:RadComboBoxItem Text="Three" Value="3" runat="server" />
</Items>
</telerik:RadComboBox>
</div>
</form>
I don't need full source for a solution, but a kick in the right direction would be much appreciated! :)
Many thanks to Veselin Vasilev and stefpet for their input. After too many hours of js debugging and ditto cups of coffee I did get this to work with IE8 and FF3.5.
The correct javascript event handler for updating parallel RadComboBoxes (responding to the OnClientSelectedIndexChanged event):
function masterChanged(sender, e)
{
var detailCB = $find("<%= DetailCB.ClientID %>");
var item = e.get_item();
var index = item.get_index(); //get selectedIndex in master
var allDetailItems = detailCB.get_items();
var itemAtIndex = allDetailItems.getItem(index); //get item in detailCB
itemAtIndex.select();
}
This can of course be shortened by doing several calls on a single line. I recon there may well be a way to do this with less code, but I tried just about everything and this is the only solution that worked for me.
You are using the client-side API of the "classic" RadComboBox while the version of the combo is for ASP.NET AJAX. Here is how your method should look like:
function masterChanged(item)
{
var detailCB = $find("<%= DetailCB.ClientID %>");
var index = item.get_selectedIndex();
detailCB.set_selectedIndex(index);
}
Here is the proper link in the documentation:
http://www.telerik.com/help/aspnet-ajax/combo_clientsidebasics.html
I have no experience with Telerik, but given what is actually rendered is a standard select list containing option elements you are able to select an option programmatically by setting the option's selected property to true.

OnClick vs OnClientClick for an asp:CheckBox?

Does anyone know why a client-side javascript handler for asp:CheckBox needs to be an OnClick="" attribute rather than an OnClientClick="" attribute, as for asp:Button?
For example, this works:
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
and this doesn't (no error):
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
but this works:
<asp:Button runat="server" OnClientClick="alert('Hi');" />
and this doesn't (compile time error):
<asp:Button runat="server" OnClick="alert('hi');" />
(I know what Button.OnClick is for; I'm wondering why CheckBox doesn't work the same way...)
That is very weird. I checked the CheckBox documentation page which reads
<asp:CheckBox id="CheckBox1"
AutoPostBack="True|False"
Text="Label"
TextAlign="Right|Left"
Checked="True|False"
OnCheckedChanged="OnCheckedChangedMethod"
runat="server"/>
As you can see, there is no OnClick or OnClientClick attributes defined.
Keeping this in mind, I think this is what is happening.
When you do this,
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
ASP.NET doesn't modify the OnClick attribute and renders it as is on the browser. It would be rendered as:
<input type="checkbox" OnClick="alert(this.checked);" />
Obviously, a browser can understand 'OnClick' and puts an alert.
And in this scenario
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
Again, ASP.NET won't change the OnClientClick attribute and will render it as
<input type="checkbox" OnClientClick="alert(this.checked);" />
As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.
You can confirm above by looking at the rendered HTML.
And yes, this is not intuitive at all.
Because they are two different kinds of controls...
You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
renders to
<input type="check" OnClick="alert(this.checked);" />
and
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
renders to
<input type="check" OnClientClick="alert(this.checked);" />
Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...
When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.
You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox_events.aspx
Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.
For those of you who got here looking for the server-side OnClick handler it is OnCheckedChanged
I was cleaning up warnings and messages and see that VS does warn about it:
Validation (ASP.Net): Attribute 'OnClick' is not a valid attribute of element 'CheckBox'. Use the html input control to specify a client side handler and then you won't get the extra span tag and the two elements.
Asp.net CheckBox is not support method OnClientClick.
If you want to add some javascript event to asp:CheckBox you have to add related attributes on "Pre_Render" or on "Page_Load" events in server code:
C#:
private void Page_Load(object sender, EventArgs e)
{
SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
}
Note: Ensure you don't set AutoEventWireup="false" in page header.
VB:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
End Sub
You can do the tag like this:
<asp:CheckBox runat="server" ID="ckRouteNow" Text="Send Now" OnClick="checkchanged(this)" />
The .checked property in the called JavaScript will be correct...the current state of the checkbox:
function checkchanged(obj) {
alert(obj.checked)
}
You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.
In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".
$(document).ready(function () {
$('input[type=checkbox]').click(function(){
var areYouSure = confirm('Are you sure you want make this change?');
if (areYouSure) {
$(this).prop('checked', this.checked);
} else {
$(this).prop('checked', !this.checked);
}
});
});
<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />
protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
using (myDataContext db = new myDataDataContext())
{
CheckBox chk = (CheckBox)sender;
RepeaterItem row = (RepeaterItem) chk.NamingContainer;
var studentID = ((Label) row.FindControl("lblID")).Text;
var z = (from b in db.StudentApplicants
where b.StudentID == studentID
select b).FirstOrDefault();
if(chk != null && chk.Checked != z.FinancialAid){
z.FinancialAid = chk.Checked;
z.ModifiedDate = DateTime.Now;
db.SubmitChanges();
BindGrid();
}
gvData.DataBind();
}
}
One solution is with JQuery:
$(document).ready(
function () {
$('#mycheckboxId').click(function () {
// here the action or function to call
});
}
);

Setting RegularExpressionValidator ValidationExpression in JavaScript

Is it possible to set the ValidationExpression of a RegularExpressionValidator using JavaScript? I'm using ASP.NET 3.5.
Here's why I want to do this...
On a payment page I have a DropDownList that allows my user to select their card type. Beneath that is a TextBox in which they type their card number.
I want to use a RegularExpressionValidator to validate that their card number is valid for their given card type. The card payment processing is performed manually in a different system, so I cannot rely on this to catch incorrect card details.
Therefore I need to use a different ValidationExpression for each card type. I would like to set the ValidationExpression using JavaScript, firing off the DropDownList onchange event.
My DropDownList is bound to an XML document:
<asp:DropDownList ID="ddlCardType" runat="server"
DataTextField="Text" DataValueField="Value"
DataSourceID="xdsCardTypes" AppendDataBoundItems="True">
<asp:ListItem Text="(select)" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:XmlDataSource ID="xdsCardTypes" runat="server"
DataFile="~/App_Data/PaymentCards.xml">
</asp:XmlDataSource>
Here's the XML doc:
<?xml version="1.0" encoding="utf-8" ?>
<PaymentCards>
<PaymentCard Text="American Express" Value="AmericanExpress" RegEx="3[47](\d{13})" />
<PaymentCard Text="MasterCard" Value="MasterCard" RegEx="5[1-5](\d{14})" />
<PaymentCard Text="Maestro" Value="Maestro" RegEx="(5018|5020|5038|6304|6759|6761)\d{8,15}" />
<PaymentCard Text="Visa" Value="Visa" RegEx="4(\d{15}|\d{12})" />
</PaymentCards>
In code-behind I'm creating a JavaScript function call and adding it to the onchange event of the DropDownList:
XDocument paymentCards = XDocument.Parse(xdsCardTypes.GetXmlDocument().InnerXml, LoadOptions.None);
List<string> regExes = paymentCards.Descendants("PaymentCard")
.Select(pc => pc.GetAttribute("RegEx").Value).ToList();
string setRegExValidatorScript = string.Format("setRegExValidator('{0}', '{1}', {2});",
ddlCardType.ClientID,
txtCardNumber_RegularExpressionValidator.ClientID,
regExes.ToJavaScriptArgumentList());
ddlCardType.AddAttribute("onchange", setRegExValidatorScript);
And in a referenced .js file I have the following:
function setRegExValidator(ddlCardTypeID, regExValidatorID, regExes)
{
var regEx = regExes[$get(ddlCardTypeID).selectedIndex];
var val = $get(regExValidatorID);
// TODO: Set the ValidationExpression!
}
So my one missing link is the ability to set the ValidationExpression from JavaScript. Yes I could use a postback to achieve this, but that seems unnecessary.
(Suggestions on an alternate approach are also welcomed!)
function setRegExValidator(ddlCardTypeID, regExValidatorID, regExes)
{
var regEx = regExes[$get(ddlCardTypeID).selectedIndex];
var val = $get(regExValidatorID);
val['validationexpression'] = regEx;
}
NB: You need to ensure that the card number is validated properly on the server-side too.

Resources