其實是不想總結這方面的內容,發現太簡單了,可是在這上面也栽了跟頭。所以還是記錄一下吧,算是提醒自己,不要太看不起太基礎的東西,有這種心理,是會載大跟頭的。
這裡模擬一下最常用的一個例子,在列表中,選擇修改,將選中的記錄,在上面顯示,並改變DropDownList中的默認選中項。

方式一
代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Wolfy.DropDownListDemo.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
編號:<asp:Literal Text="" runat="server" ID="LiteralID" /><br />
省市:<asp:DropDownList ID="DropDownListProvince" runat="server"></asp:DropDownList><br />
級別:<asp:Literal Text="" runat="server" ID="LiteralLevel" /><br />
</div>
<asp:Repeater ID="RepeaterList" runat="server">
<HeaderTemplate>
<table>
<tr>
<th>編號</th>
<th>省</th>
<th>級別</th>
<th>操作</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Eval("ID") %></td>
<td><%#Eval("Name") %></td>
<td><%#Eval("Pid") %></td>
<td>
<asp:LinkButton Text="修改" runat="server" ID="LinkUpdate" OnClick="LinkUpdate_Click" CommandArgument='<%#Eval("ID") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>
Default.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Wolfy.DropDownListDemo
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DropDownListProvince.DataSource = GetList();
DropDownListProvince.DataTextField = "Name";
DropDownListProvince.DataValueField = "ID";
DropDownListProvince.DataBind();
RepeaterList.DataSource = GetList();
RepeaterList.DataBind();
}
protected List<Province> GetList()
{
List<Province> list = new List<Province>();
list.Add(new Province() { ID = 1, Name = "北京", Pid = 0 });
list.Add(new Province() { ID = 2, Name = "上海", Pid = 0 });
list.Add(new Province() { ID = 3, Name = "河南", Pid = 0 });
list.Add(new Province() { ID = 4, Name = "河北", Pid = 0 });
list.Add(new Province() { ID = 5, Name = "湖南", Pid = 0 });
list.Add(new Province() { ID = 6, Name = "湖北", Pid = 0 });
return list;
}
protected void LinkUpdate_Click(object sender, EventArgs e)
{
LinkButton link = sender as LinkButton;
if (link != null)
{
int id = Convert.ToInt32(link.CommandArgument);
Province pro = GetList().Find(a => a.ID == id);
this.LiteralID.Text = pro.ID.ToString();
this.LiteralLevel.Text = pro.Pid.ToString();
//DropDownList的index是從零開始的 而綁定的數據的ID是從1開始的,所以為了對應需減一
//改變默認選中項
this.DropDownListProvince.SelectedIndex = pro.ID-1;
}
}
}
}