Fill with Dynamic TemplateField

1

The code that causes the error is:

 dataValue = DataBinder.Eval(container.DataItem, _columnName);

The problem is that templatefield has the following name gridview and ColumnName only reads to the point. This explains the error and read only up to the "C".

How can I make it read the whole name, including the period?

    
asked by anonymous 24.06.2014 / 13:19

1 answer

0

Using the common form of DataBinder.Eval does not really work for field names that contain . .

The alternative forms are:

((System.Data.DataRowView)Container.DataItem)["C.json"] 

or

DataBinder.GetPropertyValue(Container.DataItem, "C.json")

I particularly find the second form more elegant and simple.

This happens because DataBinder.Eval expects, in the second parameter, a expression to find the name of the column or property of a class. This way, the point influences the resolution of the parameter.

See more details about the DataBinder.Eval method in MSDN .

An example

HTML:

<asp:Repeater ID="ProductList" runat="server">
    <ItemTemplate>
        O id é: <%# DataBinder.Eval(Container.DataItem, "id") %> <br /> 
        Para o item: <%# DataBinder.Eval(Container.DataItem, "item") %> <br />
        Valor com ponto: <%# ((System.Data.DataRowView)Container.DataItem)["C.json"] %> <br />
        Outra forma: <%# DataBinder.GetPropertyValue(Container.DataItem, "C.json") %> <br />

        <br />
        <hr />
    </ItemTemplate>
</asp:Repeater>

C # no page_load to fill repeater:

protected void Page_Load(object sender, EventArgs e)
{
    var products = new DataTable();
    DataRow row;

    products.Columns.Add(new DataColumn() { ColumnName = "id" });
    products.Columns.Add(new DataColumn() { ColumnName = "item" });
    products.Columns.Add(new DataColumn() { ColumnName = "C.json"});

    for (int i = 0; i < 10; i++)
    {
        row = products.NewRow();
        row["id"] = i;
        row["item"] = "item " + i.ToString();
        row["C.json"] = "valor com . no nome";
        products.Rows.Add(row);
    }

    ProductList.DataSource = products;
    ProductList.DataBind();

}

The result:

    
24.06.2014 / 19:42