List Item dropdown - c#

I have the below code to display dropdown, but looks both name and value pairs are coming same when it displayed in dropdown.
aspx.cs:
DropDownList dp = new DropDownList();
dp.ID = ToString();
dp.Items.Add(new ListItem("test1", "This is test1"));
dp.Items.Add(new ListItem("test2", "This is test2"));
Script.DataSource = dp.Items;
Script.DataBind();
aspx:
<asp:DropDownList ID="Script" runat="server" OnSelectedIndexChanged="ScriptSelected" AutoPostBack="true">
</asp:DropDownList>
When I debug came to know that both name and value are coming same, like below
<select name="Script" onchange="javascript:setTimeout('__doPostBack(\'Script\',\'\')', 0)" id="Script">
<option value="test1">test1</option>
<option value="test2">test2</option>
</select>
but need like below
<select name="Script" onchange="javascript:setTimeout('__doPostBack(\'Script\',\'\')', 0)" id="Script">
<option value="test1">This is test1</option>
<option value="test2">This is test2</option>
</select>

You need to specify both the DataValueField and the DataTextField for your control.
<asp:DropDownList ID="Script" runat="server" OnSelectedIndexChanged="ScriptSelected" AutoPostBack="true" DataValueField="Value" DataTextField="Text">
</asp:DropDownList>
Or, if you want to do it server side,
DropDownList dp = new DropDownList();
dp.ID = ToString();
dp.DataTextField = "Text";
dp.DataValueField = "Value";
dp.Items.Add(new ListItem("test1", "This is test1"));
dp.Items.Add(new ListItem("test2", "This is test2"));
Script.DataSource = dp.Items;
Script.DataBind();

Related

Retrieving CheckBoxList Values in Function

I have a cblSchedule checkboxlist in my .ascx page that allows selection of Daily/Weekly:
<div class="form-group" id="schedule">
<label class="control-label col-md-2" id="lblSchedule">Schedule</label>
<div class="col-md-3">
<div class="input-group">
<asp:CheckboxList ID="cblSchedule" ClientIDMode="Static" CssClass="chkLabel" runat="server" AutoPostBack="false" CellPadding="5" CellSpacing="5" RepeatDirection="Horizontal" RepeatLayout="Table" onchange="ToggleSchedule(this)" >
<asp:ListItem Text="Daily" Value="Daily"></asp:ListItem>
<asp:ListItem Text="Weekly" Value="Weekly"></asp:ListItem>
</asp:CheckboxList>
</div>
</div>
</div>
There is a chkSelectDay checkboxlist displayed when Weekly is checked:
<div class="form-group" id="divSelectDay" >
<label class="control-label col-md-2" id="lblSelectDay">Select Day of Week</label>
<div class="col-md-3">
<div class="input-group">
<asp:CheckBoxList ID="chkSelectDay" CssClass="chkLabel" ClientIDMode="Static" runat="server" AutoPostBack="false" CellPadding="5" CellSpacing="5" RepeatDirection="Horizontal" RepeatLayout="Table">
<asp:ListItem Value="Monday">Mon</asp:ListItem>
<asp:ListItem Value="Tuesday">Tue</asp:ListItem>
<asp:ListItem Value="Wednesday">Wed</asp:ListItem>
<asp:ListItem Value="Thursday">Thu</asp:ListItem>
<asp:ListItem Value="Friday">Fri</asp:ListItem>
<asp:ListItem Value="Saturday">Sat</asp:ListItem>
<asp:ListItem Value="Sunday">Sun</asp:ListItem>
</asp:CheckBoxList>
</div>
</div>
</div>
I have a toggle function that display/hide chkSelectDay when Weekly is checked/unchecked in cblSchedule :
function ToggleSchedule(controlId) {
var frmControl = document.getElementById(controlId.id);
var divDay = document.getElementById("divSelectDay");
var checkbox = frmControl.getElementsByTagName("input");
var counter = 0;
for (var i = 0; i < checkbox.length; i++) {
if (checkbox[i].checked)
{
if (checkbox[i].value == "Weekly")
divDay.style.display = 'block';
}
else
{
if (checkbox[i].value == "Weekly") {
divDay.style.display = 'none';
//UNCHECK ALL chkSelectDay checkboxes <--
}
}
}
}
I would like to add in the functionality of unchecking all checkboxes in chkSelectDay when Weekly is unchecked in cblSchedule.
I tried to retrieve checkbox count via $('#chkSelectDay').
But I was unable to use .Count nor .Length, so I can't use a for-loop to set .Checked = false.
Thank you
First thing you should know is by default CheckBoxList stores its value inside ViewState and not show it in client-side. You need to add ClientValue attribute inside ListItem to let checkboxlist values available in client-side:
<asp:CheckboxList ID="cblSchedule" ClientIDMode="Static" CssClass="chkLabel" runat="server" AutoPostBack="false" CellPadding="5" CellSpacing="5" RepeatDirection="Horizontal" RepeatLayout="Table" onchange="ToggleSchedule(this)" >
<asp:ListItem Text="Daily" Value="Daily" ClientValue="Daily"></asp:ListItem>
<asp:ListItem Text="Weekly" Value="Weekly" ClientValue="Weekly"></asp:ListItem>
</asp:CheckboxList>
Then, handle change event to make sure that the Weekly value is passed, otherwise uncheck all of chkSelectDay checkboxes:
$("#cblSchedule input[type=checkbox]").change(function () {
var value = $(this).parent().attr('clientvalue');
// check if the value is 'weekly'
if (this.checked && value != "Weekly") {
// set all day selection checkboxes to 'unchecked'
$("[id*=chkSelectDay] input").removeAttr("checked");
// hide day selection checkboxes
$('#divSelectDay').css('display', 'none');
}
else {
// do something else
}
});
Related issues:
Get the Checkboxlist value when unchecked Client-Side
Check uncheck all CheckBoxes on the basis of another CheckBox
ASP.Net CheckBoxList: Check or uncheck all checkboxes client side using jQuery

Choose selected option in HTML select list from SQL

I have a select list in an ASP webpage that looks like so:
<select id="selrAF3" runat="server" onchange="selrouteonchange()" class="select">
<option class="selroute" value="V"></option>
<option class="selroute" value="I"></option>
<option class="selroute" value="Q"></option>
<option class="selroute" value="O"></option>
<option class="selroute" value="M"></option>
</select>
I have an SQL query in the codebehind that obtains one of the option values (V, I, Q, O, M), and I want the selected value in the select list to be that letter. I haven't been able to figure out how to do this. I've only found resources on populating the whole select list from an SQL query, but that's not what I want to do. I merely want the SQL query to select one of the values already there.
I'd recommend using the asp:DropdownList control instead. Generic HTML controls are limited to what you have access to.
<asp:DropDownList id="selrAF3"
OnClientChanged="selrouteonchange()" class="select"
runat="server">
<asp:ListItem Value="V"></asp:ListItem>
<asp:ListItem Value="I"></asp:ListItem>
<asp:ListItem Value="Q"></asp:ListItem>
<asp:ListItem Value="0"></asp:ListItem>
<asp:ListItem Value="M"></asp:ListItem>
</asp:DropDownList>
Then in your code behind:
selrAF3.SelectedValue = /*Your SQL Value Here*/
UPDATE
As you have your drop Down in a gridview you'll need to add an OnRowDatabound to your Gridview. Once you've done that, in the code behind you want something similar to:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddSelRAF3 = e.Row.FindControl("selrAF3") as DropDownList;
ddSelRAF3.SelectedValue = /*Your SQL Value Here*/
}
}

ASP.NET with DropDownList

I added a DropDownList from the Toolbox to the Login page on a website I'm working on.
Once I choose a ListItem in the DropDownList (in my case lets say
Gym for example...), when clicked, I want that three bars we'll be opened below my DropDownList(for example, the bars that we'll be opened are Username, Password and ID), I mean three TextBoxes beneath each other.
I think you can either try the SelectedIndexChanged event or Javascript to display the textboxes without a postback.
<select>
<option value="1">Gym 1</option>
<option value="2">Gym 2</option>
<option value="3">Gym 3</option>
<select>
At firest you put your textboxes in a panle then hide this panel and
you should set Autopostback property of you drobdownlist to True and after selecting a item in DropDownList, postback will accur. So you can show that panel include text boxes.
What you might really be needing is dynamic text boxes.
In the html part:
<asp:DropDownList runat="server" ID="DDL1" autopostback = "true" onselectedindexchanged="DDL_SelectChanged" />
<asp:PlaceHolder runat="server" ID="PH1">
</asp:PlaceHolder>
In codebehind:
void DDL_SelectChanged(object sender, EventArgs e)
{
if (DDL1.SelectedIndex == 1)
{
for (int i = 0; i < 3; i++)
{
TextBox newTB = new TextBox();
newTB.ID = "TB" + i;
PH1.Controls.Add(newTB);
}
}
}
You could use MultiveView control. And set active view index in Dropdown's selectedIndexChanged event.
I wrote some example code for you:
ASPx side:
<asp:MultiView ID="multiView" ActiveViewIndex="-1" runat="server">
<asp:View ID="viewGym" runat="server">
<asp:TextBox ID="txtBxUserName" runat="server" />
<asp:TextBox ID="txtBxPassword" runat="server" />
<asp:TextBox ID="txtBxId" runat="server" />
</asp:View>
</asp:MultiView>
<asp:DropDownList ID="Dropdownlist1" runat="server" AutoPostBack="true"
onselectedindexchanged="Dropdownlist1_SelectedIndexChanged">
<asp:ListItem Text="Choose one club" Value="0" />
<asp:ListItem Text="Gym" Value="1" />
<asp:ListItem Text="Shoppers" Value="2" />
</asp:DropDownList>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if ( IsPostBack ) //don't forget :)
return;
}
protected void Dropdownlist1_SelectedIndexChanged( object sender, EventArgs e )
{
if ( Dropdownlist1.SelectedValue == "1" ) //Gym item selected
{
multiView.ActiveViewIndex = 0; //Gym view active
}
}
If you want to any view not active when first page load then you set the ActiveViewIndex with -1 in aspx code.

How to add a data-attribute to a dropdown menu with C#

I have a standard dropdown list and am able to databind to the list.
<asp:DropDownList runat="server" ID="ddlMake" ClientIDMode="Static" DataTextField="Name" DataValueField="URL" AppendDataBoundItems="true">
<asp:ListItem>Select Make</asp:ListItem>
</asp:DropDownList>
I would like to add a data-attribute to the option like below:
<asp:ListItem data-siteid="<%# DataBinder.Eval(Container.DataItem, "SiteID") %>">Select Make</asp:ListItem>
I'm obviously getting an error because it doesn't recognize the data-siteid.
The list is databound.
Any tips would be handy
You could do this in the code-behind. I'm not sure if this is the most elegant approach, but it should work.
Dim dataSrc() As String = {"ABC", "123", "!#*#"}
drp.DataSource = dataSrc
drp.DataBind()
For i = 0 To drp.Items.Count - 1
drp.Items(i).Attributes.Add("data-siteId", dataSrc(i))
Next
Also, if this is just something which is not databound, you could consider using the HtmlSelect control which should work as well:
<select id="drp2" runat="server">
<option data-siteId="2">ABC</option>
<option data-siteId="3">123</option>
<option data-siteId="4">#*!&</option>
</select>
I ended up using a repeater since the page didn't need to repost. This allowed me not to have to work with an ondatabound event.
<asp:Repeater runat="server" ID="rptDropDown">
<HeaderTemplate>
<select id="ddlMake">
<option value="">Select Make</option>
</HeaderTemplate>
<ItemTemplate>
<option data-siteid="<%# DataBinder.Eval(Container.DataItem, "SiteID") %>" value="<%# DataBinder.Eval(Container.DataItem, "URL") %>"><%# DataBinder.Eval(Container.DataItem, "Name") %></option>
</ItemTemplate>
<FooterTemplate>
</select>
</FooterTemplate>
</asp:Repeater>
You can rewrite it with pure html if no events handling is needed:
<select>
<%foreach (var item in DataSource){%>
<option data-siteid="<%=item.SiteID%>" value="<%=item.Value%>"><%=item.Name%> </option>
<%}%>
</select>
I ended up doing this (where ds is the dataset):
for (int row = 0; row <= ds.Tables(0).Rows.Count - 1; row++) {
ddl.Items(row).Attributes.Add("data-siteid", ds.Tables(0).Rows(row)("SiteID"));
}

InitialValue does not set in RequiredFieldValidator DDL

For some reason the dropdownlist's initial value doesnt get set. It always loads some random value instead. When I look into the markup I can see all the list items including the one with -1 value. I also tried clearing browser cache and explicitly setting the SelectedIndex/Value in code to 0/"-1", but cant seem to figure out what is going on. Any idea?
Here is how I am doing it:
<asp:DropDownList ID="ddlGender" runat="server" CssClass="select_Box" OnPreRender="LoadGenders">
</asp:DropDownList>
<div class="error">
<asp:RequiredFieldValidator
ID="RequiredFieldValidatorGender"
Runat="server"
Enabled="true"
InitialValue="-1"
ControlToValidate="ddlGender"
SetFocusOnError="true"
Display="Dynamic">Gender Required</asp:RequiredFieldValidator>
</div>
Generated HTML:
<select name="pagecolumns_0$pagecontent_1$contentleftcol_0$ctl00$ddlGender" id="pagecolumns_0_pagecontent_1_contentleftcol_0_ctl00_ddlGender" class="select_Box">
<option value="-1">--Select Gender--</option>
<option selected="selected" value="M">Male</option>
<option value="F">Female</option></select>
as you can see, it is randomly selecting Male. Alsow, I notice that, last time I fill the form I set it to Male before hitting submit. May be is it caching the selection?
Here is the .cs:
protected void LoadGenders(object sender, EventArgs e)
{
if (IsPostBack) return;
((DropDownList)sender).Items.AddRange(Constants.GenderWithSelect);
}
public static ListItem[] GenderWithSelect = (new[] { new ListItem("--Select Gender--", "-1") }).Concat(Gender).ToArray();
public static ListItem[] Gender = new[]
{
(new ListItem("Male","M")),
(new ListItem("Female","F"))
};
I tried your code, and it appears that the generated html didn't have the correct field bound to the "value" of the select options.
What you must get must have this format :
<select name="ctl00$MainContent$ddlGender" id="MainContent_ddlGender" class="select_Box">
<option selected="selected" value="-1">not set</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
In order to have this, I had to set the DataValueField of the DropDownList:
<asp:DropDownList ID="ddlGender" runat="server" CssClass="select_Box" OnPreRender="ddlGender_PreRender" DataValueField="Value" DataTextField="Text">
(Just replace the DataTextField and DataValueField with the name of the properties of your class)
It turns out it has something to do with load sequence of the controls. So, adding selectedindex to LoadGenders did the trick.
protected void LoadGenders(object sender, EventArgs e)
{
if (IsPostBack) return;
((DropDownList)sender).Items.AddRange(Constants.GenderWithSelect);
((DropDownList) sender).SelectedIndex = 0;
}

Categories

Resources