使用数组中的索引作为数据值

本文关键字:数据 索引 数组 | 更新日期: 2023-09-27 18:05:05

假设我有一个DropdownList,它的数据源是一个字符串列表。我希望DataValue是列表中元素的索引

有办法做到这一点吗?

谢谢

使用数组中的索引作为数据值

您需要绑定到一个值,而不是一个计算。预先使用一个强类或在下面的示例中使用一个快速而简单的匿名类型来完成此操作。

List<string> ds = yourlist;
ddl.DataSource = yourlist
    .Select(s => new 
    { 
        Text = s, 
        Value = yourlist.IndexOf(s) 
    })
    .ToList();
ddl.DataValueField = "Value"; 
ddl.DataTextField = "Text";
ddl.DataBind();

与Flem的解决方案非常相似,但更简单。它使用Select方法的一个过载,在当前item旁边是index,它被传递。

ddl.DataSource = arrayOfStrings.Select((text, index) => new { text, index })
                               .ToList();
ddl.DataValueField = "index"; 
ddl.DataTextField = "text";
ddl.DataBind();

开始了,注意我将数据文本和值字段设置为数据集中的特定列。

SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
         DataSet ds = new DataSet();
         SqlCommand cmd = new SqlCommand("Select * from country", cn);
         SqlDataAdapter adp = new SqlDataAdapter(cmd);
         adp.Fill(ds);
         Dropdownlist1.DataSource = ds;
         Dropdownlist1.DataTextField = "CountryName";
         Dropdownlist1.DataValueField = IndexOf("CountryID");
         Dropdownlist1.DataBind();