Have Validation with DropDownList - c#

I have a DropDownList that is binded to a DataSource on the PageLoad of a page. In this DropDown List I've added a Select value as the default value. On the bottom of this drop down list and some textboxes I have a Add button. How do I add a validation on the dropdown list so that if the User leaves the value as "Select" he/she can not Click the add button unless he/she selects another value.
<asp:Label ID="lblItems" runat="server" Text="SemesterCode: "></asp:Label>
<asp:DropDownList ID="ddlItems" AppendDataBoundItems="true" runat="server">
<asp:ListItem Text=" -- Select -- " Value="-1"></asp:ListItem>
</asp:DropDownList>

Use the "onchange" method for a drop down list. When the value of the DDL is changed call a JS function that will enable the other buttons/required fields.
function validateThingy(val) {
return (val != -1)
}
function calledOnChange(val) {
if (validateThingy(val)) {
//enable the buttons
} else {
//Keep the button disabled
}
}

Check Selected index of your dropdownlist If it is 0 so alerts a message else puts your logic likewise
if(ddlItems.SelectedIndex==0){
Response.Write("Please choose any value");
}else{
//Put your logic here
}

Related

Get radio button list responses with data source asp.net

I have a radio button list that is inside of a asp repeater. it looks like this:
<asp:Repeater runat="server" ID="surveyRepeater">
<ItemTemplate>
<h3><%#((Half_Blue.Survey_files.survey_classes.surveyQuestion)Container.DataItem).questionNum%>
. <%#((Half_Blue.Survey_files.survey_classes.surveyQuestion)Container.DataItem).question%>
</h3>
<asp:RadioButtonList ID="surveyRadioList"
DataTextField="questionText"
DataValueField="valueOfQuestion" runat="server"
DataSource="<%#((Half_Blue.Survey_files.survey_classes.surveyQuestion)Container.DataItem).answerOptions %>"
RepeatDirection="Vertical">
</asp:RadioButtonList>
</ItemTemplate>
</asp:Repeater>
This displays the radio button list correctly however I cannot figure out how to get the responses in the code behind.
I can get the radio button lists by doing this:
foreach (RepeaterItem item in surveyRepeater.Items)
{
// Checking the item is a data item
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
var rdbList = item.FindControl("surveyRadioList") as RadioButtonList;
if (rdbList != null)
{
retList.Add(rdbList.SelectedValue);
}
}
}
however even though it finds all 8 of the radio button lists, the selected value is always just a empty "" string. The selected index is always -1 as well no matter which option I choose.
Any help would be greatly appreciated.
I think you are re-binding the Repeater on every PostBack. You need to wrap it inside an IsPostBack check.
if (!Page.IsPostBack)
{
surveyRepeater.DataSource = Common.LoadFromDB();
surveyRepeater.DataBind();
}
If you do not the RadioButtonLists are recreated and their selection is lost.

Get rowindex of gridview on click of a button outside gridview

In my asp.net application (v4.0), I have a grid view. I use a list object to bind data to the grid view.
In the grid view there is a cancel button. On click of the cancel button the application should pop a message to the user asking for confirmation to proceed with cancel. ie. are you sure you want to cancel the record yes/no. When the user selects yes then the particular record should be cancelled.
Now the issue is, when the user selects yes then i need to the get the index of the row for which the cancel button is clicked and i need to remove it from the list object that is used to bind the grid and rebind the gridview .
please let me know how to achieve this.
Thanks for all the reply.. im using custom pop up instead of built in 'confirm' method. The custom pop up will have 'OK' and 'Cancel' button controls. Only on click of 'OK' button i need to get the selected record index. Built in confirm method mentioned in some replies will not suit my scenario. please let me know how to achieve this.
Add a hiddenfield into your page
<asp:HiddenField ID="HiddenField1" runat="server" />
Use the Id(use corresponding column name instead of Id) of the records as the CommandArgument of Cancel button
<asp:Button ID="btncancel" runat="server" CommandArgument='<%#Eval("Id") %>' Text="Cancel" />
Then on clicking the cancel button it calls the gridviews rowcommand function. In that function keep the CommandArgument value in the hidden field as follows
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
HiddenField1.Value = e.CommandArgument.ToString();
}
Then on clicking the OK button, it calls the click event. In that function remove the Item from the List and then bind the list again to the gridview
protected void btnOK_Click(object sender, ButtonClickEventArgs e)
{
string id = HiddenField1.Value;
//use this id to remove the data from the List
// bind the gridview
}
Try this..
You can use javascript function..
<asp:Button ID="Button1" runat="server" onclientclick="Validate(this) />
Declare an HTML hidden field in your page...
<input id="Hidden1" type="hidden" runat="server" clientidmode="static"/>
function Validate(obj) {
var r = confirm("are you sure you want to cancel ?");
if (r == true) {
var id = obj.id.toString();
var index = id.split("_");
var RowNumber = index[2].toString();
document.getElementById('Hidden1').value=RowNumber ;
}
else {
return;
}
}
Here we get id of the button somewhat as ContentPlacedholde_Button1_0..Then we split it to get the index..
Use command name and command argument on cancel button like this:
<asp:Button ID="btncancel" runat="server" CommandArgument='<%#Eval("Id") %>' CommandName="Cancel" Text="Cancel" />
And then on gridviewRowcommand use this:
if (e.CommandName == "Cancel")
{
int count = GridViewName.Rows.Count;
for (int i = 0; i < count; i++)
{
int id = Convert.ToInt32(e.CommandArgument);
}
}
Have you tried adding a CommandArgument value to the cancel button that represents the item, for example an ID? Then onclick, display a popup, if the user selects yes then use the ID to remove the item from your collection, then simply rebind the grid. The item will then be gone.

asp.net radiobuttonlist will not selectindex

I have a radio button list...
<asp:RadioButtonList ID="rblCollectOptions" runat="server" CssClass="radiolist">
<asp:ListItem Value="Collect" Text="Collect from this address"></asp:ListItem>
<asp:ListItem Value="DropOff" Text="Drop off at Depot (UK only)"></asp:ListItem>
</asp:RadioButtonList>
I also have a link button on the page to "enter address manually" which I want to set the radio button to "Collect" value.
I tried...
rblCollectOptions.SelectedIndex = 0;
and
rblCollectOptions.Items[0].Selected = true;
both work if no option is already selected, but if I manually set the radio button to another option, or set a default selection, the link button does not work.
Call ClearSelection or set SelectedIndex = -1 before you set the selected item.
rblCollectOptions.ClearSelection();
or
rblCollectOptions.SelectedIndex = -1;

respond to asp:RadioButtonList changes with jquery

I have the code below with sets the focus on a textbox when the page loads and when the user selects a radio button.
How can I change this so that if they choose the last radio option "Mail" the focus is not set to
txtPayerName but instead to the btnSubmit control?
$(function () {
SetDefaultPaymentType();
$("#txtPayerName").focus();
$("#rdLstPaymentOptions").change(function () {
$("#txtPayerName").focus();
});
});
<asp:RadioButtonList ID="rdLstPaymentOptions" runat="server" RepeatColumns="3" RepeatDirection="vertical"
RepeatLayout="Flow" OnPreRender="rdBtnLst_PreRender" TabIndex="1"
ClientIDMode="Static">
<asp:ListItem Text="Credit Card " Value="CreditCard" ></asp:ListItem>
<asp:ListItem Text="Electronics Fund Transfer " Value="EFT"></asp:ListItem>
<asp:ListItem Text="Check By Mail " Value="Mail"></asp:ListItem>
</asp:RadioButtonList>
What if you set the change event on each radio button individually?
Something like:
$("#rdLstPaymentOptions").each(function (index) {
if (index == $("#rdLstPaymentOptions").length - 1) {
// insert code to set change event for last radio button
}
else {
($this).change = function () {
$("#txtPayerName").focus();
}
}
});
Give the radio button and the submit button a unique CSS class, then use:
$('.radioClass').click(function() {
$('.submitClass').focus()
})

Disabling PostBack for blank/default ListItem in DataBound DropDownList

I have a DropDownList that is populated from a datasource. After it is bound, I place an empty field at the top of the list so that it appears blank to the user (creating a sort of 'default item'). I have some code behind handling the SelectedIndexChanged event, but it doesn't really need to be executed if the user were to select the empty ListItem.
Here is my code:
.aspx
<asp:DropDownList ID="dropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropDownList_SelectedIndexChanged">
</asp:DropDownList>
C# Codebehind adding the blank ListItem
dropDownList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
dropDownList.SelectedIndex = 0;
Since I don't need the page to do a postback when the user clicks just this specific index, I want to disable postback entirely for just this listitem. Is this even possible? If so, how?
Set disabled="disabled", this will make the item not selectable (and not do postback)
<asp:DropDownList runat="server" ID="dddl">
<asp:ListItem Text="" disabled="disabled" Selected="True"></asp:ListItem>
<asp:ListItem Text="test"></asp:ListItem>
</asp:DropDownList>
Alternatively if you want to be able to select the first (empty) item but not do postback, do this:
<asp:DropDownList runat="server" ID="dddl" AutoPostBack="true" onchange="if(this.selectedIndex == 0)return false;">
<asp:ListItem Text="" Selected="True"></asp:ListItem>
<asp:ListItem Text="test"></asp:ListItem>
</asp:DropDownList>
You could add a required field validator. Then set the CausesValidation property of the DropDownList to true. This will prevent the postback and also provide the end-user feedback.
<asp:DropDownList ID="dropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropDownList_SelectedIndexChanged" CausesValidation="true">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvDropDownList" runat="server" ErrorMessage="Must select a value!" ControlToValidate="dropDownList" />
Could you add an onChange attribute to run a JS function that checks if the value is empty before posting back?
i.e.
dropDownList.Attributes.Add("onChange", "javascript: return ddlChange()");
function ddlChange
{
if(document.getElementById("<%= dropDownList.ClientID %>").value == "")
return false;
return true;
}
1.web control use postback, add attribute to cancel postback.
but option will not be selected.
protected void rblRecentOrder_DataBound(object sender, EventArgs e)
{
RadioButtonList rbl = sender as RadioButtonList;
ListItem itemX = rbl.Items.FindByText("NA");
// if no NA item then add it
if (itemX == null)
{
itemX = new ListItem("NA");
// set item cancel postback, but option will not be selected
itemX.Attributes.Add("onclick", "return false;");
}
}
2.or use javacsript call postback when need
<script>
function myPostback() {
// call asp.net postback
__doPostBack('tagName', 'params');
}
// TextBox
function updateValue(id, value) {
let obj = document.getElementById(id);
obj.value = value;
}
// Label
function updateInnerHTML(id, value) {
var obj = document.getElementById(id);
obj.innerHTML = value;
}
// DrowdownList
function setSelectOption(id, value) {
let obj = document.getElementById(id);
if (obj)
obj.value = value;
}
// RadioButtonList
function selectRadio(id) {
let obj = document.getElementById(id);
// input type=radio
if (obj) {
let items = obj.getElementsByTagName("INPUT");
for (var i = 0; i < items.length; i++) {
items[i].checked = true;
}
}
}
</script>
c#
switch(Request.Form["__EVENTTARGET"])
{
case "tageName":
var params = Request.Form["__EVENTARGUMENT"];
//..........
break;
}

Categories