Error in populating data when there are no existing records. ASP.NET C#
<p>I have two DropDownLists and one ListBox namely: ddlYearLevel, ddlSubjects, and lstStudents.</p>

<p>The ddlSubjects and lstStudents are dependent on ddlYearLevel because I set the codes like this</p>

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

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

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

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

<p>FYR:</p>

<pre><code>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();
}
</code></pre>
