我创建了一个列表数组。该数组有七行,代表一周中的几天,列表包含可用于预约医生的时段。我试图将其与 GridView 或 DataList (无论更合适的)绑定(bind),但没有成功。
我已宣布名单:
List<string>[] list=new List<string>[7]; //An array of 7 lists
for (int i = 0; i < 7; i++)
{
list[i]=new List<string>();
}
我已在列表中填写了代表可预约医生的可用时段的字符串。
我想要实现的结果是一位医生的可用性,如本网站所示:link
最佳答案
您可以将数组更改为 List<List<string>>
像这样:
List<List<string>> list = new List<List<string>>();
然后你可以将它绑定(bind)到 GridView
按照以下方式(只需适应您的情况):
protected void Page_Load(object sender, EventArgs e)
{
List<string> cols = GetColDefsFromBackend();
List<List<string>> rows = GetDataFromBackend();
GridView1.DataSource = CreateDataTable(cols, rows);
GridView1.DataBind();
}
private System.Data.DataTable CreateDataTable(List<string> columnDefinitions, List<List<string>> rows)
{
DataTable table = new DataTable();
foreach (string colDef in columnDefinitions)
{
DataColumn column;
column = new DataColumn();
column.DataType = typeof(string);
column.ColumnName = colDef;
table.Columns.Add(column);
}
// Create DataRow and Add it to table
foreach (List<string> rowData in rows)
{
DataRow row = table.NewRow();
// rowData is in same order as columnDefinitions
for (int i = 0; i < rowData.Count; i++)
{
row[i] = rowData[i];
}
table.Rows.Add(row);
}
return table;
}
/// <summary>
/// Simulates a StoredProcedureCall which returns
/// the data in a List with Lists of strings
/// </summary>
private List<List<string>> GetDataFromBackend()
{
List<List<string>> myData = new List<List<string>>();
myData.Add(Row(1));
myData.Add(Row(2));
myData.Add(Row(3));
return myData;
}
private List<string> Row(int p)
{
List<string> row = new List<string>();
for (int i = 0; i < 4; i++)
{
row.Add(string.Format("Column {0}/{1}", p, i));
}
return row;
}
private List<string> GetColDefsFromBackend()
{
List<string> cols = new List<string>();
cols.Add("Col1");
cols.Add("Col2");
cols.Add("Col3");
cols.Add("Col4");
return cols;
}
关于c# - 如何将列表数组与 GridView 或 DataList 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12989915/