我仍然不相信我的解决方案,但我认为这就是我要做的方式......
第一次加载数据时,我会用每个名称的运行日期填充字典:
private Dictionary<string, List<DateTime>> runDates = new Dictionary<string, List<DateTime>>();
private void LoadData()
{
DataTable table = new DataTable();
table.Columns.Add("TempName", typeof(string));
using (var connection = new SqlConnection("YourConnectionString"))
using (var command = new SqlCommand("SELECT DISTINCT TempName, RunDate FROM History_Table;", connection))
{
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string tempName = reader.GetString(0);
if (!runDates.ContainsKey(tempName))
{
DataRow row = table.NewRow();
row[0] = tempName;
table.Rows.Add(row);
runDates.Add(tempName, new List<DateTime>());
}
runDates[tempName].Add(reader.GetDateTime(1));
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
}
在读取每一行时,它会检查名称是否已经存在,如果不存在,则将其添加到将用于绑定 GridView 和字典的表中。然后在绑定事件中使用名称标签从字典中查找日期列表:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the label with the temp name and assign it
string tempName = (e.Row.FindControl("Label1") as Label).Value;
DropDownList ddl = e.Row.FindControl("DropDownList1") as DropDownList;
ddl.DataTextField = "RunDate";
ddl.DataValueField = "TempID";
ddl.DataSource = runDates[tempName];
ddl.DataBind();
}
}
我玩弄了各种其他想法,一个是将日期列表作为具有唯一名称列表的 xml 字段返回(很像您之前的问题),将其存储在隐藏字段中并对行数据绑定事件进行反序列化,另一种解决方案是在数据集中生成2个表并定义关系,但是这与我提出的方法原理上非常相似,我想我更喜欢这个......