Is there some elegant way to add an empty option to a DropDownList bound with a LinqDataSource?
Here's how to add a value at the top of the list. It can be an empty string, or some text.
<asp:DropDownList ID="categories" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False">
<asp:ListItem Value="-1">
-- Choose a Category --
</asp:ListItem>
</asp:DropDownList>
Be sure to set the DropDownList's AppendDataBoundItems=True.
Markup:
<asp:DropDownList ID="ddlQualQuestion" runat="server" DataSourceID="sdsQualQuestion" DataTextField="ShortQuestionText" DataValueField="QualificationQuestionKey" AutoPostBack="true" OnSelectedIndexChanged="ddlQualQuestion_SelectedIndexChanged" OnDataBound="ddlQualQuestion_DataBound" />;
Code behind:
protected void ddlQualQuestion_DataBound(object sender, EventArgs e)
{
ddlQualQuestion.Items.Insert(0, new ListItem("", "0"));
}
Taking the solution DOK provided:
<asp:DropDownList ID="categories" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False">
<asp:ListItem Value="-1">
-- Choose a Category --
</asp:ListItem>
</asp:DropDownList>
Addtionally, if you don't want to force the user to make a selection you can add a method to the LinqDataSource of your GridView:
OnSelecting="myGridview_Selecting"
Add code behind like this:
protected void myGridview_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
if (categories.SelectedValue == "-1")
{
e.WhereParameters.Remove("CategoryID");
}
}
I'd provide an extension method on IEnumerable<string> that prepended an item to the beginning of the list:
public static IEnumerable<string> Prepend(this IEnumerable<string> data, string item)
{
return new string[] { item == null ? string.Empty : item }.Union(data);
}
Its sort of linq-y, as it uses the linq extension method Union. Its a little cleaner than doing this:
var result = new string[]{string.Empty}.Union(from x in data select x.ToString());
Related
Inherited code with a dropdownlist which is used to populate some GridViews. When a selection is made in the dropdownlist, the selection does not keep and it jumps back up to the first record. A requently mentioned fix is to add the !Page.IsPostBack in the Page_Load event, however in doing so does not resolve the issue.
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="true"
DataSourceID="SqlDataSource2" DataTextField="FullAddress"
DataValueField="UniqueRecordID" Width="445px" Height="20px"
style="margin-left: 0px" TabIndex="8" AppendDataBoundItems="true"
OnSelectedIndexChanged="resetGridsAndLabel">
</asp:DropDownList>
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList2.DataSource = sqlDataSource2;
DropDownList2.DataBind();
}
Are you setting the data source for the DDL anywhere else on the page?
I have a DropDownlist inside an Edititemtemplate. I want to access the selected value from code behind.
My aspx
<EditItemTemplate>
<asp:DropDownList ID="ddlcountry" runat="server">
<asp:ListItem Text="Select Country" Value="0" disabled selected></asp:ListItem>
<asp:ListItem Text="india" Value="1"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
My aspx.cs
protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
//I want to access the dropdown value here//
}
protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
DropDownList ddlCountries = (ListView.EditItem.FindControl("ddlcountry") as DropDownList);
if(ddlCountries!=null)
{
string value=ddlCountries.SelectedValue;
}
}
<asp:DropDownList ID="ddl_Role" runat="server" DataSourceID="Sql_role"
DataTextField="Role_Name" DataValueField="Role_ID">
</asp:DropDownList>
<asp:SqlDataSource ID="Sql_role" runat="server"
ConnectionString="<%$ ConnectionStrings:Mytime_role %>"
SelectCommand="SELECT * FROM [Role_Alert]"></asp:SqlDataSource>
<asp:RequiredFieldValidator ID="Rfv_role" runat="server" ControlToValidate="ddl_role"
Display="Dynamic" ErrorMessage="*Role is Required field" Font-Italic="True" ForeColor="Red"
InitialValue="0"></asp:RequiredFieldValidator>
it gives only the starting text in database table as first value in Drop down list .so i need select as default one then the remaining list as usual
You set the selectedItem of the dropdownlist after the DataBind method.
dlTest.DataSource = // some datasource;
dlTest.DataBind();
dlTest.Items.FindByValue(search_value).Selected = true;
You can search for the item, either using FindByText or FindByValue. Alternatively, if you could store the selected item text/value, then you can set the dropdownlist selected item in the DataBound event. This will be fired after the data has been binded to dropdownlist.
protected void dlTest_DataBound(object sender, EventArgs e) {
dlTest.Items.FindByValue(search_value).Selected = true;
}
<asp:DropDownList ID="DropDownListID" AppendDataBoundItems="true" runat="server">
<asp:ListItem Text="Default text" Value="Default value" />
</asp:DropDownList>
Add a default item and also attribute AppendDataBoundItems="true"
I am using ASP.NET, I have a dropdownlist inside of a grid (radGrid).
What I like to happen is that when the dropdownlist appears, I like it to default to
"Please Select" only if the field that it is binding to is blank. Else, I like to to get the value from the DataSource.
I have the following code:
<asp:DropDownList ID="ddlEroGroup" runat="server" DataSourceID="EroGroupSource" DataTextField="Value" DataValueField="Value" AppendDataBoundItems="true" OnDataBound=" erogroupDropDown_DataBound" Text='<%# Bind("EroGroup") %>'>
</asp:DropDownList>
For the DataSource here is the code:
<asp:SqlDataSource ID="EroGroupSource" runat="server" ConnectionString="<%$ ConnectionStrings:ISQL %>"
SelectCommand="Select Value from LookupValues where Category = 'EroGroup'">
</asp:SqlDataSource>
Here is the code in the code-behind:
protected void ErogroupDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list != null)
{
list.Items.Insert(0, new ListItem("Please Select", ""));
}
}
When it does the Binding, if the value is blank, I get an error saying that it could not find the value.
try:
protected void ErogroupDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list.Items.Count.equals(0))
{
list.Items.Insert(0, new ListItem("Please Select", ""));
}
}
Use Grid PreRender event for this. May you would need to assign the value to some hidden label and access it inside prerender method and assign it to the dropdown.
<ItemTemplate>
<asp:Label runat="server" ID="lblValue" Text='<%# Eval("YourValue")%>' Visible="false" />
<asp:DropDownList ID="ddlEroGroup" runat="server" DataSourceID="EroGroupSource" DataTextField="Value" DataValueField="Value" AppendDataBoundItems="true" OnDataBound=" erogroupDropDown_DataBound" Text='<%# Bind("EroGroup") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="EroGroupSource" runat="server" ConnectionString="<%$ ConnectionStrings:ISQL %>"
SelectCommand="Select Value from LookupValues where Category = 'EroGroup'">
</asp:SqlDataSource>
</ItemTemplate>
On code behind:
protected void GridView1_PreRender(object sender, EventArgs e)
{
for(int i=0;i<Gridview1.Rows.Count;i++)
{
Label lblValue = (Label)Gridview1.Row[i].FindControl('lblValue');
DropdownList ddl = (DropdownList) Gridview1.Row[i].FindControl('ddlEroGroup');
ddl.Items.Insert(0, new ListItem("Please Select", ""));
if(lblValue!=null && !String.IsNullOrEmpty(lblValue.Text))
ddl.SelectedValue = lblValue.Text;
}
}
I have added an extra step to my uzerwizard
<asp:TemplatedWizardStep id="stpPayment" runat="server" Title="Payment">
<ContentTemplate>
<asp:DropDownList ID="cmbSubs" runat="server" ClientIDMode="Static"
Width="200px">
<asp:ListItem Value="month">Monthly Subscription</asp:ListItem>
<asp:ListItem Value="year">Annual Subscription</asp:ListItem>
</asp:DropDownList>
i am successfully navigating to the new step
protected void NewUserprofileWizard_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
if (NewUserprofileWizard.ActiveStepIndex == 0)
{
NewUserprofileWizard.ActiveStepIndex = 1;
}
}
but I cant get access to the dropdownlist from my codebehind
note: i can get a handle onto the controls in the 1st (createuser) step.
but any controls in the next step always return a null.
this is the code i am using
DropDownList cmb = (DropDownList)NewUserprofileWizard.WizardSteps[1].FindControl("cmbSubs");
i always return a null.
note that this works just fine
TextBox tmp = (TextBox)NewUserprofileWizard.CreateUserStep.ContentTemplateContainer.FindControl("Email");
userProfile.AccountEmail = tmp.Text;
problem seems unique to custom steps
Thanks for the help
Tried Gregors suggestion. no luck. mine always comes up as null.
if thsi helps any:
my wizard is inside a user control..
the page that uses the user control is inside a master page.....
Here is little sample I have created for you, first aspx code:
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" OnNextButtonClick="CreateUserWizard1_NextButtonClick">
<WizardSteps>
<asp:WizardStep runat="server" Title="My Custom Step">
<asp:DropDownList ID="cmbSubs" runat="server" ClientIDMode="Static"
Width="200px">
<asp:ListItem Value="month">Monthly Subscription</asp:ListItem>
<asp:ListItem Value="year">Annual Subscription</asp:ListItem>
</asp:DropDownList>
</asp:WizardStep>
<asp:CreateUserWizardStep runat="server" />
<asp:CompleteWizardStep runat="server" />
</WizardSteps>
</asp:CreateUserWizard>
And now the code to find first dropdown:
protected void CreateUserWizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
if (e.CurrentStepIndex == 0)
{
//get instance to dropdown...
string selectedValue = null;
string controlId = null;
foreach (var item in CreateUserWizard1.WizardSteps[0].Controls)
{
DropDownList ddl = item as DropDownList;
if (ddl != null)
{
selectedValue = ddl.SelectedValue;
controlId = ddl.ClientID;
break;
}
}
}
}
Of course you can also find your dropdown like this:
DropDownList cmbSubs = CreateUserWizard1.WizardSteps[0].FindControl("cmbSubs") as DropDownList;
Happy coding!
it appears that today my google foo was doing much better
because i am in a templateswizardstep, i have to cast the wizardstep into the templatedwizardstep.
from here i can now find the control. whooohoo!
TemplatedWizardStep step = (TemplatedWizardStep)NewUserprofileWizard.WizardSteps[1];
cmb = (DropDownList)step.ContentTemplateContainer.FindControl("cmbSubs");
Thanks all for the help