Dropdown default select value - c#

This is a Dropdown control where I am binding the data, after bind I am putting the select statement. Even though the index is kept to 0 always select comes last like this:
Current output:
india
Auz
US
--select--
Required output:
--select--
india
AUZ
US
My Code
ddlcounty.DataSource = dtNew;
ddlcounty.DataTextField = "Weight";
ddlcounty.DataValueField = "Weight";
ddlcounty.DataBind();
ddlcounty.Items.Add("--Select--");
ddlcounty.SelectedValue = "0";
What is the change required here?
Thanks

You're doing your binding first.
When you get to the part where you are adding your default condition, you're actually adding to the end of the list.
Instead of :-
ddlcounty.Items.Add("--Select--");
Do :-
ddlcounty.Items.Insert(0, new ListItem("--Select--"));
This will insert your default option as the first element of Items.
Announced edit
You won't need :-
ddlcounty.SelectedValue = 0;
.. as if you don't explicitly specify, the first item in a drop down list is automatically selected.
If, however, you want to be explicit about it, you can do the following:-
ddlcounty.Items.Insert(0, new ListItem("--Select--","0"));
ddlcounty.SelectedValue = 0;

Would you please try below way:
Just set AppendDataBoundItems to true and Insert a ListItem as selected, and 'ClearSelection' before selecting item as below.
ddlcounty.AppendDataBoundItems = true;
ddlcounty.DataSource = dtNew;
ddlcounty.DataTextField = "Weight";
ddlcounty.DataValueField = "Weight";
ddlcounty.DataBind();
ddlcounty.ClearSelection();
ddlcounty.Items.Insert(0, new ListItem { Value = "0", Text = "--Select--", Selected = true });
ddlcounty.SelectedValue = "0";

You could also declare the "select one" ListItem declaratively in your aspx page like so
<asp:DropDownList ID="ddUIC" runat="server" AppendDataBoundItems="true" Width="200px" BackColor="White" Font-Size="10px" SelectedValue='<%# Bind("Weight") %>' DataTextField="Weight" DataValueField="Weight" >
<asp:ListItem Text="Select One" Value=""></asp:ListItem>
/asp:DropDownList>
But your AppendDataBoundItems would have to be set to true
And you could still perform your databinding on the backend.

Related

RadComboBox databound not working fine for RadComboBox .selected value

<telerik:RadComboBox ID="ddlDepartment" runat="server" AutoPostBack="true"
EmptyMessage="Choose a Department"
onselectedindexchanged = "ddlDepartment_SelectedIndexChanged"
EnableLoadOnDemand="True" >
</telerik:RadComboBox>
corresponding C# databound code :
List<MdlPurchaseinvoice> objdpt = new List<MdlPurchaseinvoice>();
ddlDepartment.DataSource = SettingManager.GetDepartmentDetails();
ddlDepartment.DataTextField = "strDepartmentName";
ddlDepartment.DataValueField = "intDepartmentId";
ddlDepartment.DataBind();
now i need to programically select an item in the said combobox, for which i used
ddlDepartment.Selectedvalue = objpurchaseorder.intDepartmentId.ToString();
but unfortunately error is displayed near "Selectedvalue" as "it does not have any definition for selected value".
How can i solve this error ??
I have checked in Telerik site, SelectedValue Property Exist ,
I think you use the Wrong CASE , use SelectedValue instead of Selectedvalue
ddlDepartment.SelectedValue = objpurchaseorder.intDepartmentId.ToString();// New Code
ddlDepartment.Selectedvalue = objpurchaseorder.intDepartmentId.ToString();// OLd Code

populate CheckBoxList from query using FindByValue

I have an asp.net chckebox list:
<asp:EntityDataSource ID="GradeLevelEntityDataSource" runat="server"
ConnectionString="name=NewCourseRequestDataEntities"
DefaultContainerName="NewCourseRequestDataEntities" EnableFlattening="False"
EntitySetName="grade_levels" OrderBy="it.grade_level_index">
</asp:EntityDataSource>
<asp:CheckBoxList ID="GradeLevelCheckBoxList" runat="server" cssClass="horizontalcontrols"
DataSourceID="GradeLevelEntityDataSource"
DataTextField="grade_level_description" DataValueField="grade_level_id" AutoPostBack="True"
OnSelectedIndexChanged="CollegeInstitutionsListboxChange"
RepeatDirection="Horizontal" RepeatLayout="Flow">
</asp:CheckBoxList>
A user can return to the page, it gets the record ID, pulls the record data, and should check the appropriate checkboxes:
CheckBoxList grades = (CheckBoxList)FindControl("GradeLevelCheckBoxList");
foreach (request_grade_college r in CurrentRequest.request_grade_college)
{
ListItem grade = grades.Items.FindByValue(r.grade_level_id.ToString());
if (grade != null)
{
grade.Selected = true;
}
}
the portion of the code r.grade_level_id.ToString() does return the correct GUID, as type String. However, ListItem grade remain null, so none of the GradeLevelCheckboxList get checked.
What am I missing please?
I think that the data is not yet bound when you try to access it using Items.FindByValue(), try calling
grades.DataBind();
before the foreach loop.
Please make sure the listbox item's Value property has the correct value, if Item's Text and Value are different.
Also, Value Property and grade_level_id are exactly of same case and with trimmed spaces.

RadComboBox wrong selected value

I face the following problem when i use RadComboBox :
ddl_contactList.Items.Clear();
ddl_contactList.DataSource = ContactList.GetContactListsByDep(year, main_code);
ddl_contactList.DataTextField = "list_desc";
ddl_contactList.DataValueField = "list_code";
ddl_contactList.DataBind();
ddl_contactList.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("NewList", "-1"));
ddl_contactList.SelectedIndex = 0;
<telerik:RadComboBox ID="ddl_contactList" runat="server" AutoPostBack="True" CausesValidation="False"
CollapseDelay="0" Culture="ar-EG" ExpandDelay="0" Filter="StartsWith" ItemsPerRequest="10"
MarkFirstMatch="true" Skin="Outlook" EnableAutomaticLoadOnDemand="True" EmptyMessage="-List name-"
ShowMoreResultsBox="True"
onselectedindexchanged="ddl_contactList_SelectedIndexChanged" AppendDataBoundItems ="true">
</telerik:RadComboBox>
always the number of items in the combo box is 1 !!! although the datasource contains many items so when i try to get the selected value for any item in any time, i always get -1 !!
How to get the correct selectedvalue ?
Add the NewList item before databinding and add the following attribute to RadComboBox.
Setting AppendDataBoundItems to True preserves the items that are already present in RadComboBox. This lets you bind RadComboBox to multiple data sources or use both unbound and bound modes.
Then add the datasource to the control.
ddl_contactList.Items.Clear();
ddl_contactList.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("NewList", "-1"));
ddl_contactList.SelectedIndex = 0;
ddl_contactList.DataSource = ContactList.GetContactListsByDep(year, main_code);
ddl_contactList.DataTextField = "list_desc";
ddl_contactList.DataValueField = "list_code";
ddl_contactList.DataBind();
How about adding them individually instead of binding.
var items = ContactList.GetContactListsByDep(year, main_code);
foreach(var item in items)
{
ddl_contactList.Items.Add(new RadComboBoxItem(item.list_desc, item.list_code));
}
ddl_contactList.Items.Insert(0, new RadComboBoxItem("NewList", "-1"));
ddl_contactList.SelectedIndex = 0;

Bind Value and Range to dropdown in C# with LINQ

Quick question. Its easy enough to bind a value and text to a drop down in markup, how can I do this in C#.
To bind a single column collection
_dd_City.DataSource = LNQ.tbl_cities.Select(a => a.desc);
_dd_City.DataBind();
however say I wanted to set the value to an integer value and the text to the city name, how could I do that ??
You just need to specify the name of the properties from the objects in your collection that will be used for the text and value like this:
_ddCity.DataTextField = "desc";
_ddCity.DataValueField = "Id";
_dd_City.DataSource = LNQ.tbl_cities.Select(a => new { a.Id, a.desc});
_dd_City.DataBind();
You can set the text and value field on your markup too.
<asp:DropDownList ID="_ddCity" runat="server" DataValueField="Id" DataTextField="desc">
</asp:DropDownList>
Say your City object has members called "Id" and "CityName", you would just do this before calling DataBind:
_dd_City.DataTextField = "CityName";
_dd_City.DataValueField = "Id";
_dd_City.DataValueField="value"
_dd_City.DataTextField="key"
_dd_City.DataSource = LNQ.tbl_cities.Select(a => new {value=a.desc, key=a.id});
_dd_City.DataBind();

ListView DropDownList Edit ListView

I have created a ListView that has editing enabled, the wizard generated the table with the use of textboxes but i require the use of dropdown lists for some options.
I have created the dropdown list
<asp:DropDownList ID="ActionStatusTextBox" runat="server">
<asp:ListItem Value="Ongoing">Ongoing</asp:ListItem>
<asp:ListItem Value="Open">Open</asp:ListItem>
<asp:ListItem Value="Closed">Closed</asp:ListItem>
</asp:DropDownList>
The drop down list generates successfully but doesn't submit and enter itself in the databse.
<%# Bind("ActionStatus") %>'
The above snippet needs to used somewhere in order to bind the data but which parameter does it need attaching to to pass the data?
I've tried everything and its giving me a right headache!
Thanks
Did you try:
<asp:DropDownList .. SelectedValue='<%# Bind("ActionStatus") %>' />
The SelectedValue property doesn't appear, but I believe you can set it this way.
HTH.
What are you attempting to insert into the database? You shouldn't need to bind anything if you add your listitems manually. You could just
string value = ActionStatusTextBox.SelectedValue;
I had the same issue. Check out this thread: Why is employee_id not being inserted into database
The key was in adding a function:
Protected Sub AbsentListView_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewInsertEventArgs) Handles AbsentListView.ItemInserting
e.Values("employee_id") = DirectCast(AbsentListView.InsertItem.FindControl("ExcusedAbsences_employee_idDropDownList2"), DropDownList).SelectedValue
End Sub
Which basically set the value of the dropdown when it needed it, and once i did this, the value was going into the database.
protected void ContactsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
//Verify there is an item being edited.
if (ContactsListView.EditIndex >= 0)
{
//Get the item object.
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
// Check for an item in edit mode.
if (dataItem.DisplayIndex == ContactsListView.EditIndex)
{
// Preselect the DropDownList control with the Title value
// for the current item.
// Retrieve the underlying data item. In this example
// the underlying data item is a DataRowView object.
DataRowView rowView = (DataRowView)dataItem.DataItem;
// Retrieve the Title value for the current item.
String title = rowView["Title"].ToString();
// Retrieve the DropDownList control from the current row.
DropDownList list = (DropDownList)dataItem.FindControl("TitlesList");
// Find the ListItem object in the DropDownList control with the
// title value and select the item.
ListItem item = list.Items.FindByText(title);
list.SelectedIndex = list.Items.IndexOf(item);
}
}
}

Categories