简体   繁体   English

如何将值添加到列表数组

[英]How to add value to a List Array

I am working on a cascading drop-down for Country and City, which is working fine for now but I need to add other city as last value to the second drop down (City DD) irrespective of what country user selects. 我正在为“国家和城市”进行级联下拉菜单,该菜单现在可以正常工作,但是无论选择哪个国家/地区的用户,我都需要将other city作为最后一个值添加到第二个下拉列表(城市DD)中。 i am not able to make it work like a normal add operation to list. 我无法使其像正常的添加操作那样工作。

public CascadingDropDownNameValue[] FetchCities(string knownCategoryValues, string category)
    {
        string CountryCode;
        StringDictionary strCountries = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        CountryCode = strCountries["Country"].ToString();
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from Cities where Country=@Code Order by CityName ", con);
        cmd.Parameters.AddWithValue("@Code", CountryCode);
        cmd.ExecuteNonQuery();
        SqlDataAdapter dastate = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        dastate.Fill(ds);
        con.Close();
        List<CascadingDropDownNameValue> states = new List<CascadingDropDownNameValue>();
        foreach (DataRow dtRow in ds.Tables[0].Rows)
        {
            string StateID = dtRow["CityID"].ToString();
            string StateName = dtRow["CityName"].ToString();
            states.Add(new CascadingDropDownNameValue(StateName, StateID));
        }
        return states.ToArray();
    }

Above code is a sample code I am following this tutorial s for Cascading drop-down 上面的代码是示例代码,我正在关注本教程的级联下拉菜单

you can do this without touching your code.. simply add into the table "Cities" new row 您无需触摸代码即可执行此操作。只需在“ Cities”表中添加新行

Country = "xxx" 
CityName = "ZZZ: other country"

and then update your SQL: 然后更新您的SQL:

SqlCommand cmd = new SqlCommand("select * from Cities where Country=@Code OR Country='xxx' Order by CityName ", con);

the ZZZ at the beginning is just to make sure it is always at the end when order by CityName 开头的ZZZ只是为了确保按CityName进行订购时始终在结尾

Why not pass it as a list to the function (i don't like returning lists) as return values. 为什么不将其作为列表传递给函数(我不喜欢返回列表)作为返回值。 This way you're in control what happens to the list after getting the database values. 这样,您可以控制获取数据库值后列表发生的情况。

public void Fill()
{
    List<CascadingDropDownNameValue> cities = new List<CascadingDropDownNameValue>();

    FetchCities(cities, knownCategoryValues, category);

    cities.Add(new CascadingDropDownNameValue("new city", "0"));
}


public void FetchCities(List<CascadingDropDownNameValue> values, string knownCategoryValues, string category)
{
    string CountryCode;
    StringDictionary strCountries = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
    CountryCode = strCountries["Country"].ToString();
    con.Open();
    SqlCommand cmd = new SqlCommand("select * from Cities where Country=@Code Order by CityName ", con);
    cmd.Parameters.AddWithValue("@Code", CountryCode);
    cmd.ExecuteNonQuery();
    SqlDataAdapter dastate = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    dastate.Fill(ds);
    con.Close();
    List<CascadingDropDownNameValue> states = new List<CascadingDropDownNameValue>();
    foreach (DataRow dtRow in ds.Tables[0].Rows)
    {
        string StateID = dtRow["CityID"].ToString();
        string StateName = dtRow["CityName"].ToString();
        values.Add(new CascadingDropDownNameValue(StateName, StateID));
    }
}

UPDATE : Another nice approach would be returning IEnumerable< CascadingDropDownNameValue> 更新 :另一个不错的方法是返回IEnumerable <CascadingDropDownNameValue>

    public void Fill()
    {
        List<CascadingDropDownNameValue> cities = new List<CascadingDropDownNameValue>();

        cities.AddRange(FetchCities(connectionString, knownCategoryValues, category));

        cities.Add(new CascadingDropDownNameValue("new city", "0"));
    }


    public IEnumerable<CascadingDropDownNameValue> FetchCities(string connectionString, string knownCategoryValues, string category)
    {
        StringDictionary strCountries = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        string CountryCode = strCountries["Country"].ToString();

        using (SqlConnection con = new SqlConnection(connectionString))
        using (SqlCommand cmd = new SqlCommand("select * from Cities where Country=@Code Order by CityName ", con))
        {
            cmd.Parameters.Add("@Code", SqlDbType.VarChar).Value = CountryCode;
            using (SqlDataReader reader = cmd.ExecuteReader())
                while (reader.Read())
                {
                    string StateID = reader["CityID"].ToString();
                    string StateName = reader["CityName"].ToString();
                    yield return new CascadingDropDownNameValue(StateName, StateID);
                }
        }
    }

The advantage is that it will stream the rows and transform them to objects when needed. 好处是它将在需要时流式处理行并将其转换为对象。 This will give the advantage that if you only want a top 10. It won't get more rows from the sql-server. 这将带来的优势是,如果您只想要前10名,它将不会从sql-server中获得更多行。 (except for some row caching/block reads) (除了某些行缓存/块读取)

DataSet.Fill would get all rows before returning objects. DataSet.Fill将在返回对象之前获取所有行。 So if that table contains +1m rows. 因此,如果该表包含+ 1m行。 It will first create a DataTable with 1m rows and then returning them in objects. 它将首先创建一个包含1m行的DataTable,然后将其返回给对象。

The reason i pass the connectionstring to it, is to allow more open recordsets. 我将连接字符串传递给它的原因是为了允许更多打开的记录集。 (one open recordset per connection) (每个连接一个打开的记录集)

In this case the cities.AddRange will iterate all rows. 在这种情况下, cities.AddRange将迭代所有行。 To add only a top 10 would be: 仅添加前十名将是:

var cities = FetchCities(connectionString, knownCategoryValues, category).Take(10);
cities.AddRange(cities);

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM