0

我正在创建一个自定义控件,该控件接收 xml 文件的文件路径(字符串)和列标题、列字段的字典,并使用 CRUD 操作动态创建网格视图。我想知道的是如何通过仅使用后面的代码来复制/实现 Text='<% #Bind("field") %>' ?

我正在考虑尝试:

Dictionary<string, string> columns = new Dictionary<string, string>();

foreach (KeyValuePair<string, string> column in columns)
            {
                BoundField bField = new BoundField();
                bField.DataField = column.Value;
                bField.HeaderText = column.Key;
                GridView1.Columns.Add(bField);
            }

我愿意接受有关使用 .DataField 或 Text='<% #Bind("field") %>' 或任何我没有想到的方式是否能达到最终目标的建议。与 CRUD 一样,任何人都可以推荐一个好方法吗?也许将文本框和标签控件动态插入到gridview中?我正在使用 Visual Studio Express 2013 for Web。

4

1 回答 1

1

您覆盖 ItemDataBound 事件。如果您正在考虑为每一行动态添加控件,则最好使用不同类型的模板化控件,例如中继器。

更新- 一个例子

首先确保您处理 RowDataBound 事件(不是 ItemDataBound 我的错,那是为 DataGrid): -

    protected override void OnInit(EventArgs e)
    {
        grid.RowDataBound += grid_RowDataBound;

从列名字典中设置列(我使用了字符串数组,但你明白了): -

        var columns = new string[] { "Column 1", "Column 2", "Column 3" };

        foreach (var columnName in columns)
        {
            grid.Columns.Add(new BoundField { HeaderText = columnName });
        }

然后在 RowDataBound 事件中: -

    void grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var data = ({your object type})e.Row.DataItem;

            e.Row.Cells[0].Text = data.{fieldname};
            e.Row.Cells[1].Text = data.{fieldname};
            .
            .
            .
            e.Row.Cells[n].Text = {something};
        }
    }
于 2014-12-10T00:45:58.927 回答