C#/ASP.NET で DropDownList をソートするための最適なルート (速度や効率ではなく、シンプルさを重視) について知りたいです。いくつかの推奨事項を見てきましたが、うまくクリックできません。
編集: 皆さん、データが DropDownList に入る方法を制御できません。SQL を変更することはできません。
C#/ASP.NET で DropDownList をソートするための最適なルート (速度や効率ではなく、シンプルさを重視) について知りたいです。いくつかの推奨事項を見てきましたが、うまくクリックできません。
編集: 皆さん、データが DropDownList に入る方法を制御できません。SQL を変更することはできません。
データを含む DataTable を取得する場合は、これから DataView を作成し、ドロップダウン リストをそれにバインドできます。あなたのコードは次のようになります...
DataView dvOptions = new DataView(DataTableWithOptions);
dvOptions.Sort = "Description";
ddlOptions.DataSource = dvOptions;
ddlOptions.DataTextField = "Description";
ddlOptions.DataValueField = "Id";
ddlOptions.DataBind();
テキスト フィールドと値フィールドのオプションは、受信するデータ テーブルの適切な列にマップされます。
.NET 3.5 用の AC# ソリューション (System.Linq と System.Web.UI が必要):
public static void ReorderAlphabetized(this DropDownList ddl)
{
List<ListItem> listCopy = new List<ListItem>();
foreach (ListItem item in ddl.Items)
listCopy.Add(item);
ddl.Items.Clear();
foreach (ListItem item in listCopy.OrderBy(item => item.Text))
ddl.Items.Add(item);
}
OnPreRender など、ドロップダウン リストをバインドした後に呼び出します。
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ddlMyDropDown.ReorderAlphabetized();
}
簡単に再利用できるように、ユーティリティ ライブラリに貼り付けます。
.Net Framework の最新バージョンを実行していると仮定すると、これは機能します。
List<string> items = GetItemsFromSomewhere();
items.Sort((x, y) => string.Compare(x, y));
DropDownListId.DataSource = items;
DropDownListId.DataBind();
DropDownList は、任意の IEnumerable を DataSource として受け取ります。
LINQ を使用して並べ替えるだけです。
私は通常、データベース テーブルの値を使用して DropDownList をロードするため、最も簡単な方法は、SELECT ステートメントの ORDER BY 句を使用して結果を必要に応じて並べ替え、結果を反復処理して DropDownList にダンプすることです。
ドロップダウンリストの内容を再配置するCodeProjectのこの記事をご覧ください。データバインディングを行っている場合は、データがリストにバインドされた後にソーターを実行する必要があります。
もう 1 つのオプションは、ListItems を配列に入れてソートすることです。
int i = 0;
string[] array = new string[items.Count];
foreach (ListItem li in dropdownlist.items)
{
array[i] = li.ToString();
i++;
}
Array.Sort(array);
dropdownlist.DataSource = array;
dropdownlist.DataBind();
データを DropDownList にバインドする前にデータを並べ替えることが推奨されますが、それができない場合は、DropDownList で項目を並べ替える方法を次に示します。
まず、比較クラスが必要です
Public Class ListItemComparer
Implements IComparer(Of ListItem)
Public Function Compare(ByVal x As ListItem, ByVal y As ListItem) As Integer _
Implements IComparer(Of ListItem).Compare
Dim c As New CaseInsensitiveComparer
Return c.Compare(x.Text, y.Text)
End Function
End Class
次に、この Comparer を使用して DropDownList をソートするメソッドが必要です
Public Shared Sub SortDropDown(ByVal cbo As DropDownList)
Dim lstListItems As New List(Of ListItem)
For Each li As ListItem In cbo.Items
lstListItems.Add(li)
Next
lstListItems.Sort(New ListItemComparer)
cbo.Items.Clear()
cbo.Items.AddRange(lstListItems.ToArray)
End Sub
最後に、DropDownList を使用してこの関数を呼び出します (データバインドされた後)。
SortDropDown(cboMyDropDown)
PS 申し訳ありませんが、私の選択した言語は VB です。http://converter.telerik.com/を使用して、コードを VB から C# に変換できます。
表示された結果をアルファベット順に並べ替えるだけであれば、データベース クエリを入力するときに ORDER BY を使用して並べ替えることに同意します。データベース エンジンに並べ替えの作業を任せます。
ただし、アルファベット順以外の並べ替え順序が必要な場合もあります。たとえば、新規、オープン、進行中、完了、承認済み、クローズのような論理シーケンスが必要な場合があります。その場合、データベース テーブルに列を追加して、並べ替え順序を明示的に設定できます。SortOrder や DisplaySortOrder などの名前を付けます。次に、SQL で、並べ替え順序フィールドを (そのフィールドを取得せずに) ORDER BY します。
var list = ddl.Items.Cast<ListItem>().OrderBy(x => x.Text).ToList();
ddl.DataSource = list;
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataBind();
データバインディングに使用しているオブジェクトの種類は何ですか? 通常、Collection<T>、List<T>、または Queue<T> を使用します (状況によって異なります)。これらは、カスタム デリゲートを使用して比較的簡単に並べ替えることができます。Comparison(T) delegate に関する MSDN ドキュメントを参照してください。
それを試してみてください
-------ストアプロシージャ-----(SQL)
USE [Your Database]
GO
CRATE PROC [dbo].[GetAllDataByID]
@ID int
AS
BEGIN
SELECT * FROM Your_Table
WHERE ID=@ID
ORDER BY Your_ColumnName
END
----------Default.aspx---------
<asp:DropDownList ID="ddlYourTable" runat="server"></asp:DropDownList>
------Default.aspx.cs-------
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<YourTable> table= new List<YourTable>();
YourtableRepository tableRepo = new YourtableRepository();
int conuntryInfoID=1;
table= tableRepo.GetAllDataByID(ID);
ddlYourTable.DataSource = stateInfo;
ddlYourTable.DataTextField = "Your_ColumnName";
ddlYourTable.DataValueField = "ID";
ddlYourTable.DataBind();
}
}
----------LINQ ヘルパー クラス----
public class TableRepository
{
string connstr;
public TableRepository()
{
connstr = Settings.Default.YourTableConnectionString.ToString();
}
public List<YourTable> GetAllDataByID(int ID)
{
List<YourTable> table= new List<YourTable>();
using (YourTableDBDataContext dc = new YourTableDBDataContext ())
{
table= dc.GetAllDataByID(ID).ToList();
}
return table;
}
}
You can use this JavaScript function:
function sortlist(mylist)
{
var lb = document.getElementById(mylist);
arrTexts = new Array();
arrValues = new Array();
arrOldTexts = new Array();
for(i=0; i<lb.length; i++)
{
arrTexts[i] = lb.options[i].text;
arrValues[i] = lb.options[i].value;
arrOldTexts[i] = lb.options[i].text;
}
arrTexts.sort();
for(i=0; i<lb.length; i++)
{
lb.options[i].text = arrTexts[i];
for(j=0; j<lb.length; j++)
{
if (arrTexts[i] == arrOldTexts[j])
{
lb.options[i].value = arrValues[j];
j = lb.length;
}
}
}
}
これを試して:
/// <summary>
/// AlphabetizeDropDownList alphabetizes a given dropdown list by it's displayed text.
/// </summary>
/// <param name="dropDownList">The drop down list you wish to modify.</param>
/// <remarks></remarks>
private void AlphabetizeDropDownList(ref DropDownList dropDownList)
{
//Create a datatable to sort the drop down list items
DataTable machineDescriptionsTable = new DataTable();
machineDescriptionsTable.Columns.Add("DescriptionCode", typeof(string));
machineDescriptionsTable.Columns.Add("UnitIDString", typeof(string));
machineDescriptionsTable.AcceptChanges();
//Put each of the list items into the datatable
foreach (ListItem currentDropDownListItem in dropDownList.Items) {
string currentDropDownUnitIDString = currentDropDownListItem.Value;
string currentDropDownDescriptionCode = currentDropDownListItem.Text;
DataRow currentDropDownDataRow = machineDescriptionsTable.NewRow();
currentDropDownDataRow["DescriptionCode"] = currentDropDownDescriptionCode.Trim();
currentDropDownDataRow["UnitIDString"] = currentDropDownUnitIDString.Trim();
machineDescriptionsTable.Rows.Add(currentDropDownDataRow);
machineDescriptionsTable.AcceptChanges();
}
//Sort the data table by description
DataView sortedView = new DataView(machineDescriptionsTable);
sortedView.Sort = "DescriptionCode";
machineDescriptionsTable = sortedView.ToTable();
//Clear the items in the original dropdown list
dropDownList.Items.Clear();
//Create a dummy list item at the top
ListItem dummyListItem = new ListItem(" ", "-1");
dropDownList.Items.Add(dummyListItem);
//Begin transferring over the items alphabetically from the copy to the intended drop
downlist
foreach (DataRow currentDataRow in machineDescriptionsTable.Rows) {
string currentDropDownValue = currentDataRow["UnitIDString"].ToString().Trim();
string currentDropDownText = currentDataRow["DescriptionCode"].ToString().Trim();
ListItem currentDropDownListItem = new ListItem(currentDropDownText, currentDropDownValue);
//Don't deal with dummy values in the list we are transferring over
if (!string.IsNullOrEmpty(currentDropDownText.Trim())) {
dropDownList.Items.Add(currentDropDownListItem);
}
}
}
これは、リスト項目の Text プロパティと Value プロパティを持つ特定のドロップダウン リストを取得し、それらを特定のドロップダウン リストに戻します。幸運を祈ります!
データが System.Data.DataTable として表示される場合は、DataTable の .Select() メソッドを呼び出して、filterExpression に "" を渡し、並べ替えに "COLUMN1 ASC" (または並べ替えたい列) を渡します。これにより、指定されたとおりに並べ替えられた DataRow オブジェクトの配列が返されます。これを反復処理して、DropDownList にダンプできます。
List<ListItem> li = new List<ListItem>();
foreach (ListItem list in DropDownList1.Items)
{
li.Add(list);
}
li.Sort((x, y) => string.Compare(x.Text, y.Text));
DropDownList1.Items.Clear();
DropDownList1.DataSource = li;
DropDownList1.DataTextField = "Text";
DropDownList1.DataValueField = "Value";
DropDownList1.DataBind();
DropDownListにデータを入力する前にモデル内のデータをソートすることに同意するので、DBからこれを入力する場合は、単純なorder by句を使用してすでにソートされていることをお勧めします。あなたはWebサーバーでいくつかのサイクルを実行します.DBはそれをはるかに高速に行うと確信しています. XML ファイルなどの別のデータ ソースからこれを設定する場合は、LINQ を使用することをお勧めします。
このように簡単にできます
private void SortDDL(ref DropDownList objDDL)
{
ArrayList textList = new ArrayList();
ArrayList valueList = new ArrayList();
foreach (ListItem li in objDDL.Items)
{
textList.Add(li.Text);
}
textList.Sort();
foreach (object item in textList)
{
string value = objDDL.Items.FindByText(item.ToString()).Value;
valueList.Add(value);
}
objDDL.Items.Clear();
for(int i = 0; i < textList.Count; i++)
{
ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());
objDDL.Items.Add(objItem);
}
}
そして、この SortDDL(ref yourDropDownList); メソッドを呼び出します。以上です。ドロップダウン リストのデータが並べ替えられます。
http://www.codeproject.com/Articles/20131/Sorting-Dropdown-list-in-ASP-NET-using-C#を参照してください
データ バインドされた DropDownList を使用している場合は、ウィザードに移動して、次の方法で境界クエリを編集します。
データセットを返すオブジェクト データソースを並べ替えるには、コントロールのSortプロパティを使用します。
使用例 aspxページでColumnNameの昇順でソートする場合
<asp:ObjectDataSource ID="dsData" runat="server" TableName="Data"
Sort="ColumnName ASC" />
SQL にアクセスできない場合もありますが、DataSet または DataTable があれば、確実にSort()
メソッドを呼び出すことができます。