可能是不完美的解決方案。想法是從給定的數據表創建一個Key,Value集合。
A Dictionary
集合用於保留演講ID爲Key
和List<string>
中的相關主題爲Value
。
GridView是bind with Dictionary
和GridView的RowDataBound event
每個dropdownlist
是根據需要填充。
標記:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Key" HeaderText="Lecture ID" />
<asp:TemplateField HeaderText="Subject Name">
<ItemTemplate>
<asp:DropDownList ID="ddlSubject" runat="server" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
代碼隱藏:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//test data
DataTable dt = new DataTable();
dt.Columns.Add("LectureID", typeof(int));
dt.Columns.Add("SubjectName");
dt.Rows.Add(1, "Sub1");
dt.Rows.Add(1, "Sub2");
dt.Rows.Add(1, "Sub3");
dt.Rows.Add(1, "Sub4");
dt.Rows.Add(2, "Sub1");
dt.Rows.Add(2, "Sub4");
dt.AcceptChanges();
//Bind with GridView with Dictionary collection
GridView1.DataSource = GetDictionary(dt);
GridView1.DataBind();
}
}
//get a dictionary of distinct lectureID
private Dictionary<int, List<string>> GetDictionary(DataTable dt)
{
var dictionary = new Dictionary<int, List<string>>();
foreach (DataRow dr in dt.Rows)
{
int iKey = Convert.ToInt32(dr["LectureID"]);
if (dictionary.ContainsKey(iKey))
{
List<string> lst = dictionary[iKey] as List<string>;
lst.Add(dr["SubjectName"].ToString());
dictionary[iKey] = lst;
}
else
{
var lst = new List<string>();
lst.Add(dr["SubjectName"].ToString());
dictionary.Add(iKey, lst);
}
}
return dictionary;
}
行數據綁定事件:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
e.Row.DataItem != null)
{
DropDownList ddl = e.Row.FindControl("ddlSubject") as DropDownList;
ddl.DataSource = ((KeyValuePair<int, List<string>>)e.Row.DataItem).Value;
ddl.DataBind();
}
}
結果與相應的主題鮮明LectureID在DropDownList中:
你檢查,給出的答案? – Hassan