Choose selected option in HTML select list from SQL - c#

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*/
}
}

Related

Dynamically change radiobuttonlist name in asp.net

In my aspx file, I have a drop down list
<asp:DropDownList runat="server" ID="Dlist" CssClass="dropdown" AutoPostBack="true" SelectedIndexChanged="CtrlChanged">
<asp:ListItem Text="Select item" Value="1"></asp:ListItem>
</asp:DropDownList>
I have a radio button list
<asp:RadioButtonList ID="RadioButtonList1" RepeatColumns="1"
RepeatDirection="Vertical" RepeatLayout="Table" runat="server" AutoPostBack="true">
<asp:ListItem>Option 1</asp:ListItem>
<asp:ListItem>Option 2</asp:ListItem>
</asp:RadioButtonList>
Now I want to change the name of one or both of the radio buttons in the radio button list after something has been selected from the dropdown list using C#. Below is my attempt but not working.
protected void CtrlChanged(Object sender, EventArgs e) {
//attempting to change text of first radio button when item has been selected from dropdownlist
RadioButtonList1.SelectedIndex = 0;
RadioButtonList1.SelectedItem.Text = "Text changed!";
}
First, it is OnSelectedIndexChanged, not SelectedIndexChanged. And the ListItems of a RadioButtonList are index based, so you need to access them like this:
protected void CtrlChanged(object sender, EventArgs e)
{
RadioButtonList1.Items[0].Text = "NewValue 1";
RadioButtonList1.Items[1].Text = "NewValue 2";
}
Your way does change the text, but only for the item you set the SelectedIndex of. And it will change the selected radiobutton to the first one, should one already have been selected.

List Item dropdown

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();

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