c# - 如何将列表数组与 GridView 或 DataList 绑定(bind)?

标签 c# asp.net gridview datasource nested-lists

我创建了一个列表数组。该数组有七行,代表一周中的几天,列表包含可用于预约医生的时段。我试图将其与 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;
}

来源:Use List<List<string>> as GridView - DataSource

关于c# - 如何将列表数组与 GridView 或 DataList 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12989915/

相关文章:

c# - 是否可以让匿名类继承另一个类?

c# - 如何调用 window.alert ("message");来自 C#?

c# - ASP.NET GridView 无法隐藏列

c# - Migratordotnet 创建初始迁移

c# - 从用于外部登录身份验证的 Twitter API 获取用户的电子邮件 ASP.NET MVC C#

c# - 从 javascript 或代码隐藏 C# 函数 ASP.NET 调用服务器端 C# 函数

asp.net - 将 TemplateField 的可见性绑定(bind)到 BoundField 的内容

javascript - 如何使用 ImageButtons 在 GridView TemplateField 中保留图像超链接的样式/悬停功能

c# - "Enable Debugging of Unmanaged Code"在哪里可以在系统运行时编辑代码?

c# - 使用 ASP.NET Session 进行生命周期管理 (Unity)