PostBack Label and RequiredFieldValidator Error

Hello,

I have a Label called "lblStudentError" and three RequiredFieldValidator Controls. My problem that I'm experiencing is that when I search for a user by the users ID value I receive the error message from the Label Control which works as needed, BUT if I then reenter another ID that is correct my Label Control Erros stays displayed without clearing out. The RequiredFieldValidator fields do the same.
LVL 4
asp_net2Asked:
Who is Participating?
 
guru_samiConnect With a Mentor Commented:
I didn't look thoroughly in your code but, I guess you are not clearing your lblStudentError.
Try clearing it in your Page_Load like:

lblStudentError = String.Empty;
0
 
asp_net2Author Commented:
Please see code below.


protected void Page_Load(object sender, EventArgs e)
    {
        string authUserName = null;
        string aspUserName = null;

        authUserName = User.Identity.Name;
        aspUserName = WindowsIdentity.GetCurrent().Name;
        lblLoginUser.Value = aspUserName.Split('\\')[1];

        lblDomainUser.Text = authUserName.Split('\\')[1];
        lblLastUpdated.Value = System.DateTime.Now.ToString();
    }

    protected void imbFind_Click(object sender, ImageClickEventArgs e)
    {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PSSA"].ConnectionString);

            DataSet dsPSSA = new DataSet();
            DataTable dtStudent = new DataTable("Students");
            DataTable dtGrades = new DataTable("Grades");
            DataTable dtIEP = new DataTable("IEP");
            DataTable dtTests = new DataTable("Tests");
            DataTable dtLocations = new DataTable("Locations");

            dsPSSA.Tables.AddRange(new DataTable[] { dtStudent, dtGrades, dtIEP, dtTests, dtLocations });

            SqlCommand cmdRetrieveStudent = new SqlCommand();
            cmdRetrieveStudent.CommandText = "PSSA_RetrieveStudentValues";
            cmdRetrieveStudent.CommandType = CommandType.StoredProcedure;
            cmdRetrieveStudent.Connection = conn;

            SqlCommand cmdRetrieveGrades = new SqlCommand();
            cmdRetrieveGrades.CommandText = "PSSA_RetrieveGradeValues";
            cmdRetrieveGrades.CommandType = CommandType.StoredProcedure;
            cmdRetrieveGrades.Connection = conn;

            SqlCommand cmdRetrieveIEP = new SqlCommand();
            cmdRetrieveIEP.CommandText = "PSSA_RetrieveIEPValues";
            cmdRetrieveIEP.CommandType = CommandType.StoredProcedure;
            cmdRetrieveIEP.Connection = conn;

            SqlCommand cmdRetrieveTests = new SqlCommand();
            cmdRetrieveTests.CommandText = "PSSA_RetrieveTestValues";
            cmdRetrieveTests.CommandType = CommandType.StoredProcedure;
            cmdRetrieveTests.Connection = conn;

            SqlCommand cmdRetrieveLocations = new SqlCommand();
            cmdRetrieveLocations.CommandText = "PSSA_RetrieveLocationValues";
            cmdRetrieveLocations.CommandType = CommandType.StoredProcedure;
            cmdRetrieveLocations.Connection = conn;

            cmdRetrieveStudent.Parameters.AddWithValue("@student_id", SqlDbType.Int).Value = txtEnterStudentID.Text;

            try
            {
                conn.Open();

                SqlDataAdapter daStudent = new SqlDataAdapter();
                daStudent.SelectCommand = cmdRetrieveStudent;
                daStudent.Fill(dtStudent);

                SqlDataAdapter daGrades = new SqlDataAdapter();
                daGrades.SelectCommand = cmdRetrieveGrades;
                daGrades.Fill(dtGrades);

                SqlDataAdapter daIEP = new SqlDataAdapter();
                daIEP.SelectCommand = cmdRetrieveIEP;
                daIEP.Fill(dtIEP);

                SqlDataAdapter daTests = new SqlDataAdapter();
                daTests.SelectCommand = cmdRetrieveTests;
                daTests.Fill(dtTests);

                SqlDataAdapter daLocations = new SqlDataAdapter();
                daLocations.SelectCommand = cmdRetrieveLocations;
                daLocations.Fill(dtLocations);

                ddlGradeLevel.DataSource = dtGrades;
                ddlGradeLevel.DataValueField = "grd_id";
                ddlGradeLevel.DataTextField = "grd_level";
                ddlGradeLevel.DataBind();

                ddlIEP.DataSource = dtIEP;
                ddlIEP.DataValueField = "iep_id";
                ddlIEP.DataTextField = "iep_type";
                ddlIEP.DataBind();

                cblTests.DataSource = dtTests;
                cblTests.DataValueField = "testid";
                cblTests.DataTextField = "testname";
                cblTests.DataBind();

                ddlLocation.DataSource = dtLocations;
                ddlLocation.DataValueField = "loc_id";
                ddlLocation.DataTextField = "loc_name";
                ddlLocation.DataBind();

                if ((dtStudent != null))
                {
                    if (dsPSSA.Tables["Students"].DefaultView.Count > 0)
                    {
                        DataRow data = dsPSSA.Tables["Students"].Rows[0];
                        lblStudentID.Text = data["student_id"].ToString();
                        lblFirstName.Text = data["firstname"].ToString();
                        lblLastName.Text = data["lastname"].ToString();
                        ddlGradeLevel.SelectedValue = data["grd_id"].ToString();
                        lblInstructionalSupervisor.Text = data["teacher"].ToString();
                        lblPASecureID.Text = data["pasecureid"].ToString();
                        lblGender.Text = data["gender"].ToString();
                        lblEthnicity.Text = data["ethnicity"].ToString();
                        lblEconomicallyDisadvantage.Text = data["povertycode"].ToString();
                        lblPhone.Text = data["phone"].ToString();
                        ddlIEP.SelectedValue = data["iep_id"].ToString();
                        txtAccomadations.Text = data["spedaccnotes"].ToString();
                        ddlLocation.SelectedValue = data["loc_id"].ToString();

                        if (data.IsNull("dob"))
                        {
                            lblDOB.Text = "";
                        }
                        else
                        {
                            lblDOB.Text = ((DateTime)data["dob"]).ToString("M/d/yyyy");
                        }

                        if (data.IsNull("entrydate"))
                        {
                            lblEntryDate.Text = "";
                        }
                        else
                        {
                            lblEntryDate.Text = ((DateTime)data["entrydate"]).ToString("M/d/yyyy");
                        }

                        foreach (DataRow Row in dtStudent.Rows)
                        {
                            if (!(Row.IsNull("testid")))
                            {
                                cblTests.Items.FindByValue(Row["testid"].ToString()).Selected = true;
                            }
                        }

                    }
                    else
                    {
                        // Reset labels if data isn't found
                        lblStudentID.Text = "";
                        lblFirstName.Text = "";
                        lblLastName.Text = "";
                        lblDOB.Text = "";
                        lblInstructionalSupervisor.Text = "";
                        lblPASecureID.Text = "";
                        lblEntryDate.Text = "";
                        lblGender.Text = "";
                        lblEthnicity.Text = "";
                        lblEconomicallyDisadvantage.Text = "";
                        lblPhone.Text = "";
                        txtAccomadations.Text = "";

                        lblStudentError.Text = "Student ID does not exist";
                    }
                }
            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }

            finally
            {
                conn.Close();
            }
    }

    protected void imbSubmit_Click(object sender, ImageClickEventArgs e)
    {
        // Check to see if user selected at least one checkbox value
        if ((cblTests.SelectedIndex == -1))
        {
            lblSelectOneCheckBox.Text = "REQUIRED";
        }
        else
        {
            lblSelectOneCheckBox.Text = "";

            lblStudentError.Visible = true;

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PSSA"].ConnectionString);

            SqlCommand cmdUpdateStudentData = new SqlCommand();
            cmdUpdateStudentData.CommandText = "PSSA_UpdateStudentData";
            cmdUpdateStudentData.CommandType = CommandType.StoredProcedure;
            cmdUpdateStudentData.Connection = conn;

            cmdUpdateStudentData.Parameters.AddWithValue("@student_id", SqlDbType.Int).Value = lblStudentID.Text;

            SqlCommand cmdInsertStudentTests = new SqlCommand();
            cmdInsertStudentTests.CommandText = "PSSA_InsertStudentTests";
            cmdInsertStudentTests.CommandType = CommandType.StoredProcedure;
            cmdInsertStudentTests.Connection = conn;

            cmdUpdateStudentData.Parameters.AddWithValue("@grd_id", SqlDbType.Int).Value = ddlGradeLevel.SelectedItem.Value;
            cmdUpdateStudentData.Parameters.AddWithValue("@iep_id", SqlDbType.Int).Value = ddlIEP.SelectedItem.Value;
            cmdUpdateStudentData.Parameters.AddWithValue("@loc_id", SqlDbType.Int).Value = ddlLocation.SelectedItem.Value;

            if (txtAccomadations.Text == string.Empty)
            {
                cmdUpdateStudentData.Parameters.Add("@spedaccnotes", SqlDbType.VarChar, 500).Value = DBNull.Value;
            }
            else
            {
                cmdUpdateStudentData.Parameters.Add("@spedaccnotes", SqlDbType.VarChar, 500).Value = txtAccomadations.Text;
            }

            if (lblEconomicallyDisadvantage.Text == string.Empty)
            {
                cmdUpdateStudentData.Parameters.Add("@povertycode", System.Data.SqlDbType.VarChar, 10).Value = DBNull.Value;
            }
            else
            {
                cmdUpdateStudentData.Parameters.Add("@povertycode", System.Data.SqlDbType.VarChar, 10).Value = lblEconomicallyDisadvantage.Text;
            }

            if (lblLoginUser.Value == string.Empty)
            {
                cmdUpdateStudentData.Parameters.Add("@loginuser", System.Data.SqlDbType.VarChar, 50).Value = DBNull.Value;
            }
            else
            {
                cmdUpdateStudentData.Parameters.Add("@loginuser", System.Data.SqlDbType.VarChar, 50).Value = lblLoginUser.Value;
            }

            if (lblLastUpdated.Value == string.Empty)
            {
                cmdUpdateStudentData.Parameters.Add("@lastupdated", System.Data.SqlDbType.VarChar, 50).Value = DBNull.Value;
            }
            else
            {
                cmdUpdateStudentData.Parameters.Add("@lastupdated", System.Data.SqlDbType.VarChar, 50).Value = lblLastUpdated.Value;
            }

            try
            {
                conn.Open();

                // Add student_id Parameter for PSSA_InsertStudentTests
                cmdInsertStudentTests.Parameters.AddWithValue("@student_id", System.Data.SqlDbType.Int).Value = lblStudentID.Text;

                // Add testid Parameter for PSSA_InsertStudentTests
                cmdInsertStudentTests.Parameters.AddWithValue("@testid", System.Data.SqlDbType.Int);

                // Execute Delete Stored Procedure before Insert/Update Stored Procedure
                SqlCommand cmdDeleteStudentTests = new SqlCommand();
                cmdDeleteStudentTests.CommandText = "PSSA_DeleteStudentTests";
                cmdDeleteStudentTests.CommandType = CommandType.StoredProcedure;
                cmdDeleteStudentTests.Connection = conn;

                cmdDeleteStudentTests.Parameters.AddWithValue("@student_id", SqlDbType.Int).Value = lblStudentID.Text;

                // Execute the cmdDeleteStudentTests SqlCommand
                cmdDeleteStudentTests.ExecuteNonQuery();

                // Execute the cmdUpdateStudentData SqlCommand
                cmdUpdateStudentData.ExecuteNonQuery();

                foreach (ListItem item in cblTests.Items)
                {
                    if (item.Selected)
                    {
                        cmdInsertStudentTests.Parameters["@testid"].Value = item.Value;
                        cmdInsertStudentTests.ExecuteNonQuery();
                    }
                }

                // Execute the update after adding listitem tests values command
                cmdUpdateStudentData.ExecuteNonQuery();

                Label3.Text = "Student is now signed up for PSSA";

            }
            catch (Exception ex)
            {
                Label2.Text = ("Error on update: " + ex.Message.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
    }
0
 
asp_net2Author Commented:
that is correct guru_sami..

I tried adding your snippet in there but that didn't work :(
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
guru_samiCommented:
Are you using Ajax ...i mean updatepanels or other javascript?
0
 
asp_net2Author Commented:
no
0
 
guru_samiCommented:
On your second try, you are posting back right? I mean after entering correct ID you are pressing the search button?
Can you set breakpoint at the line lblStudentError = String.Empty; which you added in page_Load and see if that is executed?
Also are you sure your validators are set correctly....to validate the correct ID, because if not, the you know that the ID is correct, but the validators don't know that it is correct.

Please share your .aspx code that involves these validators and all.
0
 
asp_net2Author Commented:
>> On your second try, you are posting back right? I mean after entering correct ID you are pressing the search button?

Yes

>> Can you set breakpoint at the line lblStudentError = String.Empty; which you added in page_Load and see if that is executed?

Yes, when I run the page after setting a breakpoint then it displays the information for the breakpoint, but the application stops there.

>> Also are you sure your validators are set correctly....to validate the correct ID, because if not, the you know that the ID is correct, but the validators don't know that it is correct.

Yes.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="secure_index" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>PACYBER - PSSA Application</title>
    <link rel="stylesheet" href="../css/pssa.css" type="text/css" />
    <!--[if lte IE 8]>
           <style type="text/css" media="all">
           @import "../css/ie8.css";
           </style>
        <![endif]-->
</head>
<body>
    <form id="form1" runat="server">
    <div id="wrapper">
        <img src="../images/logo.png" class="image" alt="PA Cyber Logo" />
        <div id="header">
            <p class="number">
                Welcome,
                <asp:Label ID="lblDomainUser" runat="server"></asp:Label>
            </p>
        </div>
        <div id="content">
            <br />
            <p class="EnterStudentID">
                Enter Student ID:
                <asp:TextBox ID="txtEnterStudentID" CssClass="textbox" runat="server"></asp:TextBox>
                <asp:ImageButton ID="imbFind" CssClass="imgFind" runat="server" ImageUrl="~/images/btn_find.png"
                    OnClick="imbFind_Click" /><asp:Label ID="lblStudentError" CssClass="studenterror"
                        runat="server"></asp:Label>
            </p>
            <p class="bg">
                Student ID:
                <asp:Label ID="lblStudentID" runat="server" CssClass="labelValue"></asp:Label>
            </p>
            <p class="altbg">
                First Name:
                <asp:Label ID="lblFirstName" runat="server" CssClass="labelValue"></asp:Label>
            </p>
            <p class="bg">
                Last Name:
                <asp:Label ID="lblLastName" runat="server" CssClass="labelValue"></asp:Label>
            </p>
            <p class="altbg">
                Grade Level:
                <asp:DropDownList ID="ddlGradeLevel" CssClass="ddl" runat="server">
                </asp:DropDownList>&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ddlGradeLevel"
                    InitialValue="6" CssClass="ddlRequired" ErrorMessage="REQUIRED"></asp:RequiredFieldValidator>
            </p>
            <p class="bg">
                Date of Birth:
                <asp:Label ID="lblDOB" runat="server" CssClass="labelValue"></asp:Label>
            </p>
            <p class="altbg">
                Instructional Supervisor:
                <asp:Label ID="lblInstructionalSupervisor" runat="server" CssClass="labelValue"></asp:Label>
            </p>
            <p class="bg">
                PA Secure ID:
                <asp:Label ID="lblPASecureID" runat="server" CssClass="labelValue"></asp:Label>
            </p>
            <p class="altbg">
                Entry Date:
                <asp:Label ID="lblEntryDate" runat="server" CssClass="labelValue"></asp:Label>
            </p>
            <p class="bg">
                Gender:
                <asp:Label ID="lblGender" runat="server" CssClass="labelValue"></asp:Label>
            </p>
            <p class="altbg">
                Ethnicity:
                <asp:Label ID="lblEthnicity" runat="server" CssClass="labelValue"></asp:Label>
            </p>
            <p class="bg">
                Economically Disadvantaged:
                <asp:Label ID="lblEconomicallyDisadvantage" runat="server" CssClass="labelValue"></asp:Label>
            </p>
            <p class="altbg">
                Phone Number:
                <asp:Label ID="lblPhone" runat="server" CssClass="labelValue"></asp:Label>
            </p>
            <p class="bg">
                IEP:
                <asp:DropDownList ID="ddlIEP" CssClass="ddl" runat="server">
                </asp:DropDownList>&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ddlIEP"
                    InitialValue="1" CssClass="ddlRequired" ErrorMessage="REQUIRED"></asp:RequiredFieldValidator>
            </p>
            <p class="altbg">
                Accomadations:
                <asp:TextBox ID="txtAccomadations" TextMode="MultiLine" Width="200px" MaxLength="500"
                    Columns="4" Rows="4" CssClass="multilinetextbox" runat="server"></asp:TextBox>
            </p>
            <br />
            <br />
            <br />
            <br />
            <p class="bgcheckbox">
                Choose a Test(s):
                <asp:CheckBoxList ID="cblTests" runat="server" CssClass="checkbox" RepeatDirection="Horizontal"
                    TextAlign="Right" RepeatColumns="2">
                </asp:CheckBoxList>
                <asp:Label ID="lblSelectOneCheckBox" CssClass="RequiredCheckBoxList" runat="server"></asp:Label>
            </p>
            <p class="altbg">
                Location:
                <asp:DropDownList ID="ddlLocation" CssClass="ddl" runat="server">
                </asp:DropDownList>&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="ddlLocation"
                    InitialValue="30" CssClass="ddlRequired" ErrorMessage="REQUIRED"></asp:RequiredFieldValidator>
            </p>
            <br />
            <asp:Label ID="Label3" runat="server"></asp:Label><asp:Label ID="Label1" runat="server"></asp:Label><asp:Label
                ID="Label2" runat="server"></asp:Label>
            <asp:HiddenField ID="lblLoginUser" runat="server" />
            <asp:HiddenField ID="lblLastUpdated" runat="server" />
            <asp:ImageButton ID="imbSubmit" runat="server" CssClass="imgSubmit" ImageUrl="~/images/btn_submit.png"
                OnClick="imbSubmit_Click" />
        </div>
        <div id="footer">
        </div>
    </div>
    </form>
</body>
</html>
0
 
guru_samiCommented:
Let me ask you: So you have two separate sections:
1: Search
2: Some form that takes input correct?

What I am thinking is your validators are fired, which shouldn't when you click search button. They should fire only when you click imbSubmit button

So for that to happen
1: set ValidationGroup property for your  imbSubmit and the Validators to some value.
e.g. ValidtionGroup="SubmitValidaiton"

2: Set CausesValidation =false for your imbFind, because you don't want other validators on page to fire when you are searching.
0
 
asp_net2Author Commented:
>> Let me ask you: So you have two separate sections:
1: Search
2: Some form that takes input correct?

I have a Page_Load, imbFind Click Event, and imbSubmit Click Events.

Not sure, who to implement what you are asking me to do. I have 3 separate RequiredFieldValidaotr Controls.

0
 
guru_samiConnect With a Mentor Commented:
How about for now just do this:

2: Set the property CausesValidation =false for your imbFind button
0
 
asp_net2Author Commented:
Ok, that seemed to help. Now for the Label Control "lblStudentError". If I enter an invalid ID then this Label display the error message, but if I enter a correct ID then the Label still stays displayed rather than going away.
0
 
guru_samiCommented:
So now when you enter correct ID, you are getting right results to display?

You still have this in your page load right: lblStudentError = String.Empty; ??
How about adding the same in imbFind_Click ="if" block.

Then set breakpoints on this like of else block:

          lblStudentError.Text = "Student ID does not exist";
0
 
asp_net2Author Commented:
>> So now when you enter correct ID, you are getting right results to display?

Yes, but the label that shows when a user does not exist is still displayed.

>> You still have this in your page load right: lblStudentError = String.Empty; ??
How about adding the same in imbFind_Click ="if" block.

Not sure what and where to add this part.
0
 
guru_samiCommented:
 if ((dtStudent != null))
 {
         lblStudentError = String.Empty;
   //rest of your code
}

Set breakpoint on line lblStudentError = String.Empty;
and also on this line:
  lblStudentError.Text = "Student ID does not exist";

Please post your debugging results.
0
 
asp_net2Author Commented:
not sure why it works but it does. All I did was added the lblStudentError.Text = String.Emtpy; to just the page load and it works fine now. Confused.... :(
0
 
guru_samiCommented:
--->All I did was added the lblStudentError.Text = String.Emtpy;
I think you already added that as in my first post.
0
 
asp_net2Author Commented:
yes, but why do i not have to add anything in for the imbFind code?
0
 
guru_samiCommented:
i didn't get that. You have things working or it is still failing?
0
 
asp_net2Author Commented:
working now, thanks to your help. But I thought that you wanted me to also add something for the imbFind Click Event code.
0
 
guru_samiCommented:
Yes, I wanted...when it wasn't working(your comment#33702780), But if it is working as desired, no need for it.
0
 
asp_net2Author Commented:
sorry, i meant to award point not CLOSE the post.
0
 
asp_net2Author Commented:
Hi guru_same,

Not sure what happened but I'm trying to close this post with awarding you A but for some reason it will not let me close this post and award you point.
0
 
guru_samiCommented:
I don't know but, moderator will be able to close it based on your this comment:

"Notice: asp_net2 has requested that this question be closed by accepting guru_sami's comment #33702169 (250 points) as the solution and guru_sami's comment #33702757 (250 points) as the assisted solution for the following reason:
thank you for all your help!!!!"
0
 
asp_net2Author Commented:
ok, not sure what i hit, but want to make sure you get awared with an A. Thanks again guru_sami..
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.