Error in populating data when there are no existing records. ASP.NET C#
===

please help me in solving my problem.

I have two DropDownLists and one ListBox namely: ddlYearLevel, ddlSubjects, and lstStudents.

The ddlSubjects and lstStudents are dependent on ddlYearLevel because I set the codes like this

    protected void ddlYearLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulateSubjects(int.Parse(ddlYearLevel.SelectedItem.Value));
            PopulateStudent(int.Parse(ddlSubjects.SelectedValue), int.Parse(ddlYearLevel.SelectedValue));
        }

If I have existing records of Subjects for the selected YearLevel, then there's no problem.

But when I have no existing recods of Subjects, that's the time the error appears stating "Input String was not in a correct format".

My problem is, how can I set the value to null if there are no records?

FYR:

    private void PopulateSubjects(int yearLevel)
        {
            
                con1.Open();
                SqlCommand com = new SqlCommand();
                com.Connection = con1;
                com.CommandType = CommandType.Text;
                com.CommandText =
                    "SELECT Subjects.SubjectID, Subjects.SubjectCode, Subjects.YearID " +
                    "FROM Subjects WHERE Subjects.YearID = " + yearLevel;
                SqlDataReader data = com.ExecuteReader();
    
                if (data != null)
                {
                    ddlSubjects.DataSource = data;
                    ddlSubjects.DataValueField = "SubjectID";
                    ddlSubjects.DataTextField = "SubjectCode";
                    ddlSubjects.DataBind();
                }
    
                else
                {
                    lblAdd.Text = "No records found!";
                }
    
                data.Close();
                con1.Close();
                con1.Dispose();      
        }

    private void PopulateYearLevel()
        {
            con5.Open();
            SqlCommand com = new SqlCommand();
            com.Connection = con5;
            com.CommandType = CommandType.Text;
            com.CommandText =
                "SELECT * FROM YearLevels";
            SqlDataReader data = com.ExecuteReader();
            ddlYearLevel.DataSource = data;
            ddlYearLevel.DataValueField = "YearID";
            ddlYearLevel.DataTextField = "YearLevel";
            ddlYearLevel.DataBind();
    
            data.Close();
            con5.Close();
            con5.Dispose();
        }