Mohsen Sarkar
Mohsen Sarkar

Reputation: 6030

Why DataBinding can't find a property which exist?

I have declared a class but when I try to access it's members I get the following error :
DataBinding: 'reapTest.Toop' does not contain a property with the name 'Rang'.

WebForm1.aspx.cs :

namespace reapTest {

    public class Toop {
        public string Rang;
        public int Gheymat;
    }

    public static class MyData {

        public static Toop[] TP = new Toop[] { new Toop() { Rang = "Ghermez", Gheymat = 100 }, new Toop() { Rang = "Yellow", Gheymat = 44 } };
        public static Toop[] RT() {
            return TP;
        }

    }

    public partial class WebForm1 : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {

        }
    }
}

WebForm1.aspx :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="reapTest.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
            <ItemTemplate>
                <%#Eval("Rang")%>
            </ItemTemplate>
        </asp:Repeater>

        <asp:ObjectDataSource runat="server" ID="ObjectDataSource1" SelectMethod="RT" TypeName="reapTest.MyData"></asp:ObjectDataSource>
    </div>
    </form>
</body>
</html>

Upvotes: 0

Views: 1440

Answers (1)

David W
David W

Reputation: 10184

I believe it is because it is looking for a literal property named Rang. You have a field named Rang, but that's not the same as a property, to-wit:

EDIT: Code sample

public class Toop {

     // These values are *fields* within the class, but *not* "properties." 
     private string m_Rang; // changing these field decls to include m_ prefix for clarity
     private int m_Gheymat; // also changing them to private, which is a better practice

     // This is a public *property* procedure
     public string Rang     
     {
         get
         {
             return m_Rang;
         }
         set
         {
             m_Rang = value;
         }
     }
}

Fields and Properties are related in that Properties provide a public "wrapper" mechanism to the "private" field data of each instance of the class. But it is critical to note that they are separate concepts, and not interchangeable. Merely having a field declaration (also called a member in some object parlance) does not expose it as a property. Note what @FrédéricHamidi said - the docs state the "value of the expression parameter must evaluate to a public **property**"(emphasis mine).

As noted in this excerpt directly from Microsoft, EVAL, one way or the other, has to have a property.

enter image description here

Hopefully that helps.

Upvotes: 7

Related Questions