How to dynamically Order a listbox with a dropdown? - c#

I have a listbox with 20 colors. It looks something like this:
1:Red
2:Green
3:Blue
4:Orange
5:Red
6:Yellow
7:Orange
8:Red
9:Green
....
It gets the data from an ObjectDataSource which in turn gets it's data from a method which returns a datatable. I want a dropdown which basically has 2 items, Order By # and Order By Color. If the user chooses Order By #, it will Order the ListBox in ascending or descending order. If the user chooses Order By Color, it will Order By Color. How do I go about doing this?
Can I sort this using a DataView?
Thanks,
XaiSoft

You can add the sort expression to your ObjectDataSource as a Select parameter, you can define it like so:
<asp:ObjectDataSource
ID="ObjectDataSource1"
runat="server"
SelectMethod="SelectMethod"
TypeName="MyDataObject">
<asp:Parameter Direction="input" Type="string" Name="sortExpression">
</asp:Parameter>
</asp:ObjectDataSource>
Then in the "SelectMethod" method where the data is retrieved add a parameter of that name and return a DataView:
public DataView SelectMethod(string sortExpression)
{
DataTable table = GetData();
DataView dv = new DataView(table);
dv.Sort = sortExpression;
return dv;
}
Then in the wizard for the ObjectDataSource you can bind that Parameter to the dropdown SelectedValue. Make the value of each of the DropDown items the same as your column names.

(I'm assuming you've already figured out how to bind the ListBox in the first place.)
Set the property AutoPostback="true" on your DropdownList. This will cause the SelectedIndexChanged event to fire when the user picks a different value.
In there you can rebind your listbox.
Edit: deleted my misunderstanding around the ObjectDataSource - joshperry's answer covers that much better!

Just wonder... You already have the data in the ListBox, why not sorting it using javascript? To avoid go back to the server and ask for the same thing.
just get the correct list box id and you're done!
<script language="JavaScript" type="text/javascript">
function sortlist() {
var lb = document.getElementById('mylist'); // <-- Use $get(<%# myList.ClientID %>); if you want
arrTexts = new Array();
for(i=0; i<lb.length; i++) {
arrTexts[i] = lb.options[i].text;
}
arrTexts.sort();
// arrTexts.reverse() // <-- uncomment if you want descending
for(i=0; i<lb.length; i++) {
lb.options[i].text = arrTexts[i];
lb.options[i].value = arrTexts[i];
}
}
</script>
<select name="mylist" id="mylist" size="5">
<option value="Anton">Anton</option>
<option value="Mike">Mike</option>
<option value="Peter">Peter</option>
<option value="Bill">Bill</option>
<option value="Carl">Carl</option>
</select>
<br />
sort

Related

Hide or Remove duplicate options in dropdownlist

I'm using WebForms. In my Form, I have a dropdownlist control. Sometimes the Select option gets added twice in my from. How can remove this duplicate option or hide it?
I've tried to count how many times Select option is added then hide it but wasn't successful.
The reason why it's adding it twice is because grdview_Color_DataBound gets called twice.
<select name="ctl00$MainContent$grdview_Color$ctl10$ddl_Grd_Color" id="MainContent_grd_ddl_grdview_Color" class="form-control dropdown">
<option value="0" selected="selected" disabled="disabled">Select</option>
<option value="0" disabled="disabled">Select</option>
<option value="Yellow">Yellow</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
</select>
protected void grdview_Color_DataBound(object sender, EventArgs e)
{
ListItem firstItem = new ListItem("Select", "0");
firstItem.Attributes.Add("disabled", "disabled");
ddl.DataSource = dataSource;
ddl.DataTextField = TextField;
ddl.DataValueField = ValueField;
ddl.DataBind();
ddl.Items.Insert(0, firstItem);
}
A naive way would be to store the items in the drop down list in some kind of container like a list. Clear the drop down items and then loop through your container, only adding unique items back to the drop down items list with something like:
// Save the items
savedItems = dropDownItems.Items;
// Clear The items
dropDownItems.Items.Clear();
// Go through the container adding unique items to the drop down list
foreach (string item in savedItems){
if (!dropDownItems.Items.Contains(item)) {
dropDownItems.Items.Add(item);
}
}
of course this way is not the best way, but it is a way if you are in a hurry.
You need to set the AppendDataBoundItems property to true to preserve the existing values in the DDL. You also need to ensure that you are not doing it on every postback - your code sample does not show if and how you are doing this in the Page_Load() method.

Disable selection from Radcombobox list of values

I want to list all the items in the radcombobox (Values are binded from dataset) but user should not be allowed to select any value from radcombobox.
User should able to see all the items but selecting an item should be disabled.
I would appreciate any help. Thanks in advance.
You can do it in aspx part of the page. Right in this way.
<telerik:RadComboBox x:Name="radComboBox" Width="200">
<telerik:RadComboBoxItem Content="Alapattah" IsEnabled="False"/>
<telerik:RadComboBoxItem Content="Brickell Avenue" />
<telerik:RadComboBoxItem Content="Downtown Miami" IsEnabled="False"/>
</telerik:RadComboBox>
But if you are binding it programatically, you can do something like this:
foreach(RadComboBoxItem item in radComboBox.Items)
{
item.Enabled = false;
}
Then in both cases user can view, but can't select disabled items.
More info is here: http://docs.telerik.com/devtools/wpf/controls/radcombobox/howto/enable-disable-radcombobox-items
Assign the data to the RadComboBox.DataSource. Then disable the combobox. "Name" and "Value" must be a part of your dataset returned from the stored proc.
In this example, I am using a EntityFramework lambda expression to get list of Users.
The table has 3 column - UserId, Name, Salary
combo.DataSource = dbCtx.tbl_users.Where(u => u.salary > 1000).OrderBy(u => u.user_id).ToList();
combo.DataTextField = "Name"
combo.DataValueField = "UserId";
combo.Enabled = false;

Bind Same Data To Multiple Drop Down Lists

I have 10 drop down lists on my page 5 are for employee names and they are labeled ddlemp1, ddlemp2, ddlemp3, ddlemp4, ddlemp and I have 5 drop down lists for level and they are labeled ddllvl1, ddllvl2, ddllvl3, ddllvl4, ddllvl5
Is it possible to bind the same items to all my drop down lists that are like ddlemp and bind a second set of choices to all drop down lists that are named like ddllvl?
And I am populating the drop down lists like so:
this.ddlemp1.Items.Insert(1, new ListItem("Fran", "14"));
this.ddlemp1.Items.Insert(2, new ListItem("George", "3")):
EDIT
Would a repeater work in my instance as I have one drop down list of each on a row in my table, and from my understanding of a repeater Each element I need to be "repeated" should fall under the same repetaer. So unless I could nest a ddllvl repeater inside my ddlemp repeater somehow?
<asp:Repeater ID="RepeateDropDownListSelections" runat="server">
<tr id="row6" runat="server">
<td><asp:DropDownList ID="ddlemp6" runat="server" Height="16px" Width="278px"></asp:DropDownList></td>
<td class="style2"><asp:DropDownList ID="ddllvl6" runat="server" Height="16px" Width="45px"></asp:DropDownList></td>
</tr>
</asp:Repeater>
Instead of adding the list items to your drop downs, instead add them to a separate list and bind that to each control. For example:
var employees = new List<ListItem>
{
new ListItem("Fran", "14"),
new ListItem("George", "3")
};
ddlemp1.DataSource = employees;
ddlemp1.DataBind();
ddlemp2.DataSource = employees;
ddlemp2.DataBind();
...
ddlemp5.DataSource = employees;
ddlemp5.DataBind();
Repeat the same for your other list.

Dropdown List will not populate

I'm not sure how to correct the following problem. I have dropdown list that has a object data source. Then in the code there is a method like this
void InitPageData()
{
MembershipUser user = Membership.GetUser();
DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
DataSet.MemberInfoDataTable dt = da.GetMember((Guid)user.ProviderUserKey);
if (dt.Rows.Count == 1)
{
DataSet.MemberInfoRow mr = dt[0];
//rank.Text = mr.rank;
//position.Text = mr.position;
UserName.Text = user.UserName;
...
}
This method populates form fields on the page. What I'm trying to do is to have the rank dropdown list populated from the ods but use this method above to populate the selected item of the rank dropwon list with the line rank.Text = mr.rank. In this example the the line of code that throws the error is commented out otherwise it throws this: "'rank' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value".
I've chaned the code to rank.DataTextFiled = mr.rank and rank.DataValueField = mr.rankid.ToString() but this threw another error: "DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Star'." "Star" is the value of the mr.rank.
Here is what the dropdown list and the ods look like:
<asp:DropDownList runat="server" ID="rank" CssClass="txtfield" DataSourceID="ODCRanks"
DataTextField="Rank" DataValueField="ID" AppendDataBoundItems="True">
<asp:ListItem Text="--- Select a Rank ---" Value="-1" />
<asp:ObjectDataSource ID="ODCRanks" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetRanks"
TypeName="RanksTableAdapters.RankTableAdapter"></asp:ObjectDataSource>
You should try adding data columns to your data tables (with ID and Rank being the column name) so that the data can be binded to control.
The Text property sets it by value.
See http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.text.aspx
You seem to have what will be the text associated with the value and you want to set that as the selected item. I guess this mostly because your value collection is bound to something called ID and I figure a rank of Star isn't an ID.
If Star is what will show up as something in DataTextField, use the items collection FindByText method to select it.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitemcollection.findbytext.aspx
Example
ListItem li = DropDownList1.Items.FindByText("one");
if (li != null) li.Selected = true;
If Star is indeed an ID, then check that the collection is fully loaded before trying to select anything in it.
try something like
rank.SelectedIndex = rank.Items.IndexOf(rank.Items.FindByText(mr.rank));

Getting value as DateTime, but displaying as DateTime.Year in DropDownList (with LINQ)

In the database, I have a table 'Years', that contains columns for 'YearId', 'YearStart' and 'YearEnd' (don't ask me why, its not my database).
I need to populate an asp:DropDownList with the different year values in the table, ie. I need the dropdown to be like:
//pseudocode
<select>
<option>2010</option>
<option>2011</option>
..etc..
</select>
But since the 'YearStart' and 'YearEnd' are stored in DateTime format, I'm getting this:
//pseudocode
<select>
<option>1/1/2010 12:00:00 AM</option>
<option>1/1/2011 12:00:00 AM</option>
..etc..
</select>
Here is how I am currently populating the DropDownList:
dropDownList.DataSource = DataContext.Years;
dropDownList.DataValueField = "YearId";
dropDownList.DataTextField = "YearStart";
dropDownList.DataBind();
Basically, I need the dropDownList.DataTextField to be in DateTime.Year form, ie:
//pseudocode
dropDownList.DataTextField = ("YearStart").Year;
So what would be the best way to populate the dropDownList and achieve what I need?
You can try including DataTextFormatString
dropDownList.DataTextFormatString = "{0:YYYY}";
or
you can tweak the DataSource like this
dropDownList.DataSource = DataContext.Years.Select(y => new {y.YearID, YearStart = y.YearStart.Year})
.ToList();
Assuming you don't want to change the data source itself, I suspect you'd use:
dropDownList.DataTextField = "YearStart.Year";
Basically you provide a binding path, not necessarily just a single property name.
Try changing your data binding code to just: (using System.Linq of course)
dropDownList.DataSource = DataContext.Years.Select(d => d.Year);
dropDownList.DataBind();
You can get all LINQy but I'd just do:
dropDownList.DataTextFormatString = {0:yyyy};
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.datatextformatstring.aspx

Categories

Resources