Robert
Robert

Reputation: 1726

ASP.NET - Use variable in .aspx page

I'm trying to access a variable or property in my .cs file from the .aspx file but not having any luck. I've looked at several threads on here and have tried them all but still no luck. Here's the scenario; I've got a GridView control with textboxes and a RequiredFieldValidator in one row:

<asp:TemplateField HeaderText="User Name" ItemStyle-Width="10px">
    <ItemTemplate>
        <asp:Label ID="lblWebLogin" runat="server" Text='<%#Eval("WebLogin") %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtWebLogin" runat="server" Text='<%#Eval("WebLogin") %>'></asp:TextBox>
        <asp:RequiredFieldValidator ID="rfvEditWebLogin" runat="server" 
            ControlToValidate="txtWebLogin" Display="None" ErrorMessage='<%= this.LoginRequired %>'></asp:RequiredFieldValidator>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtWebLogin" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>

There is a ValidationSummary control on the form which is working because I can set the ErrorMessage to a literal string and see that it works.

Here's the code from my .cs:

public string LoginRequired
{
    get { return "Error, please try again"; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        BindDataToGrid();
}

private void BindDataToGrid()
{
    DataTable dt;
    SqlCommand sc = new SqlCommand();
    DAL oDAL = new DAL(DBInformation.Instance.CurrentEncodedConnectionString, DBInformation.Instance.ConnectionTimeout);

    //Get User Information.
    sc.CommandText = Constants.StoredProcedureNames.GetUsers;
    dt = oDAL.SPDataTable(sc, "AllUsers");
    gvUsers.DataSource = dt;

    foreach (DataRow dr in dt.Rows)
        lUser.Add(new User());

    gvUsers.DataBind();
}

any ideas as to why it's not working?

Upvotes: 1

Views: 10266

Answers (1)

Mubarek
Mubarek

Reputation: 2689

Change this

ErrorMessage='<%= this.LoginRequired %>'

in to this

ErrorMessage='<%# this.LoginRequired %>'

and call DataBind() in page load

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
  {
    DataBind();
    BindDataToGrid();
 }
}

Upvotes: 2

Related Questions