VotingDemoDataContext db = new VotingDemoDataContext();
var x = (from name in db.Elections select name);
int n = x.Count();
Election election = new Election();
election.ElectionID = n.ToString();
Constituency c=new Constituency();
election.ConstituencyId = Convert.ToInt32(from m in db.Elections where (c.ConstituencyName==ddlConstitency.SelectedItem.Text) select m.ConstituencyId);
election.Date = Convert.ToDateTime(txtDate.Text);
election.ElectionType = ddlEType.SelectedItem.Text;
election.EO = txtEOName.Text;
election.EOPassword = txtEOPassword.Text;
db.Elections.InsertOnSubmit(election);
db.SubmitChanges();
txtEOPassword.Text = "";
txtDate.Text = "";
txtResultDate.Text = "";
ddlConstitency.SelectedIndex = 0;
ddlEType.SelectedIndex = 0;
txtEOName.Text = "";
此代码为以下行返回null异常:election.ConstituencyId = Convert.ToInt32(from m in db.Elections where (c.ConstituencyName==ddlConstitency.SelectedItem.Text) select m.ConstituencyId);
where (c.ConstituencyName==ddlConstitency.SelectedItem.Text)
我敢打赌问题就在这里。。。你可能已经为你的下拉列表选择了一个值,但是你刚刚创建了Constituency对象。。。在创建对象之后,我没有看到为该ConstituencyName设置任何属性。因此,您正在将dropdownlist中的有效值与某个默认ConstituencyName或null进行比较。查询将失败,因为没有匹配项-equals求值将始终失败。