我認爲你正在尋找(確保雖然不是100%),這樣的事情
在aspx頁面:
<asp:DropDownList ID="DropDownListOfWeapon" runat="server" OnSelectedIndexChanged="DropDownListOfWeapon_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
<br /><br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
在後面的代碼:
protected void Page_Load(object sender, EventArgs e)
{
//check for postback
if (!IsPostBack)
{
//fill the dropdown
DropDownListOfWeapon.DataSource = GetWeapons();
DropDownListOfWeapon.DataTextField = "Name";
DropDownListOfWeapon.DataValueField = "Id";
DropDownListOfWeapon.DataBind();
//add a select text at the first position
DropDownListOfWeapon.Items.Insert(0, new ListItem("Select a weapon", "-1", true));
}
}
private List<Weapon> GetWeapons()
{
//create a new list
List<Weapon> weaponList = new List<Weapon>();
//fill the list with dummy weapons
//this probly would come from a database or other external source
for (int i = 0; i < 10; i++)
{
Weapon weapon = new Weapon();
weapon.Id = i;
weapon.Name = "Weapon " + i;
weapon.Attack = "Attack " + i;
weapon.SortOfWeapon = "Sort of weapon " + i;
weaponList.Add(weapon);
}
//sort the list alphabetically
weaponList = weaponList.OrderBy(x => x.Name).ToList();
return weaponList;
}
protected void DropDownListOfWeapon_SelectedIndexChanged(object sender, EventArgs e)
{
//get the id from the dropdown
int Id = Convert.ToInt32(DropDownListOfWeapon.SelectedValue);
if (Id < 0)
{
//clear the literal when no selection is made
Literal1.Text = "";
}
else
{
//get the correct weapon from the list based on it's id using Linq
List<Weapon> weaponList = GetWeapons().Where(x => x.Id == Id).ToList();
//show the properties in the literal
Weapon weapon = weaponList[0];
Literal1.Text = weapon.Id + "<br />";
Literal1.Text += weapon.Name + "<br />";
Literal1.Text += weapon.Attack + "<br />";
Literal1.Text += weapon.SortOfWeapon + "<br />";
}
}
//the weapon class
class Weapon
{
public int Id { get; set; }
public string Name { get; set; }
public string Attack { get; set; }
public string SortOfWeapon { get; set; }
}
請訪問http:/ /stackoverflow.com/questions/38150214/asp-net-how-to-create-cascading-dropdownlists-boxes-using-single-data-table/39230066#39230066?你的問題看起來相似 – VDWWD
你的意思是採取其他的值是什麼?您是否在尋找級聯下拉菜單(因此您先選擇一個項目,然後用相關數據填充另一項目),或者您是否希望選擇下拉列表中的項目,然後訪問所有屬性選擇的項目? 如果代碼示例是關於武器的,爲什麼要寫地址問題呢?讓任何人都難以給你一個相關的例子! – Matt
@VDWWD對不起,但我不明白你的例子。我怎麼能適用於selectedItem的屬性?在webforms中,如果我使用List <>作爲DataSourse,我可以應用於SelectedItem的所有屬性。 – cruim