3

C#を使用してasp.netにドロップダウンリストを作成する方法があります

public void get_country_box_populated(ref System.Web.UI.WebControls.DropDownList dropDown, bool add_initial_text)
{
    dropDown.Items.Clear();
    //dropDown.Items.Add(0,"Select Any Country");
    var context = new db_vmartEntities();
    var query = from c in context.tbl_countary
                where c.status == true
                select new { c.countary_id, c.countary_name };

    var dictionary = new Dictionary<int, string>();
    if (add_initial_text)
    {
        dictionary.Add(0, "Select Any Country");
    }
    foreach (var item in query)
    {
        dictionary.Add(item.countary_id, item.countary_name);
    }
    dropDown.DataTextField = "Value";
    dropDown.DataValueField = "Key";
    dropDown.DataSource = dictionary;  //Dictionary<int, string>
    dropDown.DataBind();
}

ここで、編集ページで次のようなデフォルト値を選択する必要があります。

store_registration my_store = str.get_store_by_id(Session["user"].ToString(), sid);
c.get_country_box_populated(ref countary_box,false);
countary_box.Text = countary_box.Items.FindByValue(my_store.countary).ToString();

しかし、パターンはこのようなものであるため、値は設定されていません

Dictionary<key,value>
Dictionary<5,Pakistan>
Dictionary<8,India>
Dictionary<9,Iran>
Dictionary<6,UK>

mystore.country の値が 6 のときにドロップダウンリストに UK を設定できるかどうかのヘルプまたはガイド

4

2 に答える 2

2

まず、ComboBox参照渡しする必要はありません。

DataBoudComboBoxの値を選択するには、次のようにします。

countary_box.SelectedValue = my_store.countary_id; //im not 100% sure that this is the key, so change it to equivalent of item.countary_id

そして、それは与える価値を事前に選択します。

于 2013-02-07T08:56:49.973 に答える
0

問題は次の行にあると思います。

countary_box.Text = countary_box.Items.FindByValue(my_store.countary).ToString();

ASP.NET では、(Winforms のように)のSelectedValueプロパティを介してTextプロパティを設定できます。DropDownList違いに注意してください。値は text プロパティで設定します。ただしListItem.ToString、値のプロパティではなくテキストを返します。

したがって、これが必要です:

countary_box.Text = my_store.countary.ToString(); // if countary is the int which is used as key 

またはSelectedValue直接使用して同じ:

countary_box.SelectedValue = my_store.countary.ToString();  
于 2013-02-07T08:59:56.170 に答える