我有两个 DropDownLists 和一个 ListBox,即:ddlYearLevel、ddlSubjects 和 lstStudents。
ddlSubjects 和 lstStudents 依赖于 ddlYearLevel 因为我设置了这样的代码
protected void ddlYearLevel_SelectedIndexChanged(object sender, EventArgs e)
{
PopulateSubjects(int.Parse(ddlYearLevel.SelectedItem.Value));
PopulateStudent(int.Parse(ddlSubjects.SelectedValue),
int.Parse(ddlYearLevel.SelectedValue));
}
如果我有所选 YearLevel 的现有科目记录,那么就没有问题。
但是,当我没有现有的主题记录时,就会出现错误,指出“输入字符串的格式不正确”。
我的问题是,如果没有记录,如何将值设置为 null?
财政年度:
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();
}