Where should I put new ListItem for DropDownList - c#

I have a page with 1 main DropDownList and 2 other. Made it to choose settings for printing report.
The problem is - I use DataSources in these DropDownLists but they haven't an empty value. Where should I put adding a new empty value into DropDownList for correct work?
There is my code (in a comment is a thing that i need to add)
protected void ddlMain_Load(object sender, EventArgs e)
{
switch (ddlMain.SelectedValue)
{
case "1":
dFirst.Visible = true;
dSecond.Visible = false;
break;
case "2":
dFirst.Visible = false;
dSecond.Visible = true;
break;
}
<div>
<asp:DropDownList ID="ddlMain" runat="server" AutoPostBack="true" OnLoad="ddlMain_Load">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2 " Value="2"></asp:ListItem>
</asp:DropDownList>
</div>
<div runat="server" id="dFirst" visible="false">
<asp:DropDownList ID="ddlFirst" runat="server" DataSourceID="sdsFirst"
DataTextField="name" DataValueField="id" OnLoad="ddlFirst_Load">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsFirst" runat="server"
ConnectionString="<%$ ConnectionStrings:conStr %>">
</asp:SqlDataSource>
</div>
//ddlFirst.Items.Add(new ListItem("--Select--", "-1"));
I tried OnLoad secondary element, OnLoad main DropDownList and Page_Load. They don't fit me because new ListItem don't appears when page firstly loading or added more than 1 time when page refreshes.

Use Insert method in page load.
ddlAcademicYear.Items.Insert(0, new ListItem("-- Select --", "-1"));
0 is position at which you want to insert.

Add an optionlabel to your dropdownlist and assign the text "--Select--". Your dropdownlist should now have the desired default value.

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.

Dropdown add default name

I have a dropdown it contain all country names.The code is working fine but I need to add a default choice in the dropdown.How to add a default choice?(<--choose-->).
my code is
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ddlCountryofOrgin.ascx.cs" Inherits="UserControls_DataType_ddlCountryofOrgin" %>
<asp:DropDownList ID="ddlCountry" CssClass="ddlCountry" runat="server" DataValueField="english_name"
DataSourceID="sqlCountry" OnPreRender="ddlCountry_PreRender" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged" />
<asp:SqlDataSource ID="sqlCountry" runat="server" SelectCommand="SELECT [country_id],[english_name], danish_name FROM [dbo].[nano_country] WHERE [is_active] = 1 ORDER BY [sort_order] DESC, [english_name] ASC" />
Thanks in advance for help...
Set AppendDataBoundItems as True
and add item to dropdownlist:
<asp:ListItem Selected="True" Value="0">--Choose--</asp:ListItem>
Code:
<asp:DropDownList ID="ddlCountry" CssClass="ddlCountry" runat="server" AppendDataBoundItems = "True" DataValueField="english_name"
DataSourceID="sqlCountry" OnPreRender="ddlCountry_PreRender" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged" >
<asp:ListItem Selected="True" Value="0">--Choose--</asp:ListItem>
</asp:DropDownList >
protected void Page_Load(object sender, system.EventArgs as e)
{
ddlCountry.Items.Insert(0,"--Choose--");
}
Try this code
ddlCountry.Items.Insert(0, new ListItem("Select","--Choose--")

If statement on dropDownList listItem

I need to add a condition to a DropDownList where a method can be executed by button click only if the user has selected a value different than the listItem (default value).
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True"
DataSourceID="SqlDataSource5"
DataTextField="proj_name" DataValueField="proj_name">
<asp:ListItem Text="Select a project to clone" Value="" />
</asp:DropDownList>
How can I structure an if condition to validate that the selected value is not the ListItem (default value)?
You can use asp.net delivered validation controls
Ex:
<asp:RequiredFieldValidator id="rfv1"
ControlToValidate="DropDownList1"
Display="Static"
ErrorMessage="* Select a value"
InitialValue="DefaultValueHere"
runat="server"
ValidationGroup="V1"/>
Then edit your button markup to use ValidationGroup
<asp:Button Id="button1" ValidationGroup="V1" .../>
In your codebehind button click code add this
protected void button1_onlick(Object sender, EventArgs e)
{
If(Page.IsValid)
{
// your existing code here
}
}
See sample code below
if (DropDownList1.SelectValue == "")
{
// Write your code here
}
you can also have:
if (DropDownList1.Text == "Select a project to clone")
{
// Write your code here
}

how to maintain dropdownlist selected item after click of a button on the same page

im using an update panel whose update mode is set to conditional. i want to maintain the drop down list selection after I click a button which displays a form to enter information that pertains to that particular selected dropdownlist selection. how can this be done? i enabled view state of the dropdownlist itself to be tru but it isnt working... the list value always goes back to the original default value - 0
<asp:DropDownList ID="DropDownListTug" runat="server" DataSourceID="SqlDataSourceTugs"
DataTextField="Tug_Name" DataValueField="Tug_ID" AutoPostBack="True" AppendDataBoundItems="True"
OnSelectedIndexChanged="ShowNewRateBtn">
<asp:ListItem Value="0" Text="<Select>" Enabled="True" Selected="True"></asp:ListItem>
</asp:DropDownList>
<asp:Button ID="NewTug" runat="server" Text="New Tug" OnClick="NewTug_Click"
CausesValidation="False" Width="74px" />
<asp:SqlDataSource ID="SqlDataSourceTugs" runat="server" ConnectionString="<%$ g %>"
SelectCommand="SELECT [Tug_Name], [Tug_ID] FROM [COMIS_tbl_TugMaster]"></asp:SqlDataSource>
protected void ShowNewRateBtn(object sender, EventArgs e)
{
BtnNewRate.Visible = true;
}
protected void BtnNewRate_Click(object sender, EventArgs e)
{
try
{
processTugs.Visible = true;
allButtons.Visible = true;
BtnSave.Visible = true;
BtnCancel.Visible = true;
// DropDownListTug.Focus();
// DropDownListTug.EnableViewState = true;
// DropDownListTug.SelectedValue = Session.... ;
// }
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}enter code here
<asp:ListItem Value="0" Text="<Select>" Enabled="True" Selected="True"></asp:ListItem>
If you see this line in your GridView code i think you are providing a default value to your dropdown everytime it binds .
Your selection will be lost because of this attribute :-
Selected="True"
i made a silly mistake quite really.. in my Cancel function which i called in the New Rate function, i cleared the selection in there. removed it and its working fine now... thanks alot

adding option to drop down list

I have a drop down list with multiple values. I have a list item named "Other". When selecting other I want to generate a text box with required field validator. I have written like this:
Markup:
<asp:DropDownList ID="dl_test_name" runat="server"
OnSelectedIndexChanged="SelectedIndexChanged"
Height="22px" Width="103px">
<asp:ListItem>Science</asp:ListItem>
<asp:ListItem>Maths</asp:ListItem>
<asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="tb_other" runat="server" Width="94px" Visible="False">
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ControlToValidate="tb_other" ErrorMessage="*">
</asp:RequiredFieldValidator>
Code-behind:
protected void SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dropDownList = (DropDownList)sender;
if (dropDownList.SelectedValue == "Other")
{
tb_other.Enabled = true;
tb_other.Text = string.Empty;
tb_other.Visible = true;
}
else
{
tb_other.Enabled = false;
tb_other.Text = dropDownList.SelectedValue;
}
}
but when selecting on any list item ,control doesn't go to SelectectedIndexChanged event. Only after reloading the page does it work.
What is the problem?
To make your DropDownList post back to the server you need to use the AutoPostback property, like this:
<asp:DropDownList ID="dl_test_name" runat="server"
OnSelectedIndexChanged="SelectedIndexChanged"
Height="22px" Width="103px" AutoPostBack="true">
Arathy, make AutopostBack property of dropdown to true in aspx

Categories

Resources