我正在编写一个程序,我向sql添加了一个数学类,但是对一些外键使用了组合框,这样他们只能从引用表中的某些项中选择(例如类名来自不同的表,包含所有类名。但是由于某种原因,当我使用combobox.selectedvalue函数时,classnameid没有给出正确的id。它继续给出奇怪的-14和-25作为id的错误。请帮助。这里是我的代码
private void btnAddClass_Click(object sender, EventArgs e)
{
int iclassroomID = Convert.ToInt16(cmbClassRoomName.SelectedValue);
int iclassTypeID = Convert.ToInt16(cmbClassType.SelectedValue);
int iHours = Convert.ToInt16(cmbHours.SelectedItem);
int iMins = Convert.ToInt16(cmbMinutes.SelectedItem);
string sClassLength = txtLength.Text;
DateTime dtClassdate;
dtClassdate = dateTimePicker1.Value;
DateTime myClassDateandTime = dtClassdate.Date.AddHours(iHours).AddMinutes(iMins);
txtOutput.Text = Convert.ToString(iclassroomID);
int selectedyear = this.dateTimePicker1.Value.Year;
int selectedmonth = this.dateTimePicker1.Value.Month;
int selectedday = this.dateTimePicker1.Value.Day;
int thisyear = Convert.ToInt16(DateTime.Now.Year);
int thismonth = Convert.ToInt16(DateTime.Now.Month);
int thisday = Convert.ToInt16(DateTime.Now.Day);
if (cmbSchool.SelectedIndex == 0)
{
MessageBox.Show("Please Select A School");
}
else if (cmbClassRoomName.SelectedIndex == 0)
{
MessageBox.Show("Please Select A Classroom");
}
else if (cmbClassType.SelectedIndex == 0)
{
MessageBox.Show("Please Select A Class Type");
}
else if (cmbHours.SelectedIndex == 0)
{
MessageBox.Show("Please Select the hour for the starting time of the class");
}
else if (cmbMinutes.SelectedIndex == 0)
{
MessageBox.Show("Please Select the minute for the starting time of the class");
}
else if (selectedyear < thisyear)
{
MessageBox.Show("Please Select a date forward from today");
}
else if (selectedmonth < thismonth)
{
MessageBox.Show("Please Select a date forward from today");
}
else if (selectedday < thisday)
{
MessageBox.Show("Please Select a date forward from today");
}
else if (txtLength.Text == "")
{
MessageBox.Show("Please enter the class length");
}
else
{
classTableAdapter.AddClass(iclassroomID, iclassTypeID, myClassDateandTime, sClassLength);
this.Validate();
this.classBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.geared4MathDataSet);
MessageBox.Show("Class Added");
this.Close();
}
}
private void cmbSchool_SelectedIndexChanged(object sender, EventArgs e)
{
int iclassroomname = Convert.ToInt16(cmbSchool.SelectedValue);
try
{
this.classRoomTableAdapter.FillBySchool(this.geared4MathDataSet.ClassRoom, iclassroomname);
lblClassroomName.Visible = true;
cmbClassRoomName.Visible = true;
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
http://imgur.com/FRl2Uew,0slWYAq 有我的表格。该链接上有2个上传。单击第二页以查看第二页
答案 0 :(得分:0)
看不出任何明显可以打破的东西 你能提供一些样本输入吗? 当您调试代码(获得-14,-25的地方)时,对象是正确的对象吗?
代码改进建议:
话虽如此,你的变量名称......缺乏......
我理解cmbClassRoomName
,但所有iNames
或dtNames
都不需要这些前缀。此外,如果您确实选择使用类型和驼峰案例,iclassTypeID
应为iClassTypeID
。
另一个问题是i
前缀表明它是一个接口,而不是一个int。
关于你的验证if / else阻止......为什么会存在?你在使用WinForm / WPF / ASP吗?你考虑过使用验证吗?这可能是第一次有点滑稽,但是值得花时间学习金币,将你的代码分离,这样一切都更有意义。