【问题标题】:How to set Dropdownlist value in asp.net using C#如何使用 C# 在 asp.net 中设置 Dropdownlist 值
【发布时间】:2013-01-22 17:05:42
【问题描述】:

我有一种方法可以使用 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();

但是没有设置值,因为patteren是这样的

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

如果我可以在 mystore.country 值为 6 时在下拉列表中设置 UK 的任何帮助或指导

【问题讨论】:

    标签: c# asp.net dictionary


    【解决方案1】:

    首先你不需要通过引用传递ComboBox

    要选择DataBoud ComboBox 的值,请执行以下操作:

    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
    

    它会预先选择赋予价值。

    【讨论】:

      【解决方案2】:

      我认为问题出在这一行:

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

      在 ASP.NET 中,您可以通过 Text propertyDropDownList 设置 SelectedValue 属性(就像在 Winforms 中一样)。请注意区别,您通过 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();  
      

      【讨论】:

        猜你喜欢
        • 2021-10-24
        • 1970-01-01
        • 1970-01-01
        • 2010-09-22
        • 1970-01-01
        • 2019-12-15
        • 1970-01-01
        • 2011-11-18
        • 2019-02-20
        相关资源
        最近更新 更多