this.dropDownList3.DataSource = dr;出现System.NullReferenceException:“未将对象引用设置到对象的实例。”
区域:
"dropDownList3" runat="server" AutoPostBack="True" OnSelectedIndexChanged="dropDownList3_SelectedIndexChanged1" >
城市:
"dropDownList4" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
//在网页第一次打开的时候进行调用
if (!IsPostBack)
{
this.dataBind();
}
}
protected void dataBind()
{
SqlConnection sqlcon = DB.sqlcon();
sqlcon.Open();
SqlCommand sqlcom = new SqlCommand("select * from dis", sqlcon);
SqlDataReader dr = sqlcom.ExecuteReader();
this.dropDownList3.DataSource = dr;
this.dropDownList3.DataValueField = "disId";
this.dropDownList3.DataTextField = "disName";
this.dropDownList3.DataBind();
dr.Close();
sqlcom.CommandText = "select * from pro";
SqlDataReader dr1 = sqlcom.ExecuteReader();
this.dropDownList4.DataSource = dr1;
this.dropDownList4.DataValueField = "proId";
this.dropDownList4.DataTextField = "proName";
this.dropDownList4.DataBind();
dr1.Close();
sqlcon.Close();
}
protected void dropDownList3_SelectedIndexChanged1(object sender, EventArgs e)
{
int disID = Convert.ToInt32(this.dropDownList3.SelectedItem.Value);
SqlConnection sqlcon = DB.sqlcon();
sqlcon.Open();
SqlCommand sqlcom = new SqlCommand("select * from pro where disId= ' " + disID + " '", sqlcon);
SqlDataReader dr = sqlcom.ExecuteReader();
this.dropDownList4.DataSource = dr;
this.dropDownList4.DataValueField = "proId";
this.dropDownList4.DataTextField = "proName";
this.dropDownList4.DataBind();
dr.Close();
sqlcon.Close();
}
- [ ]
dropDownList 是 DataSource 需要指定为 DataTable 类型,你这里的 dr 类型不对,你用 .Fill 填充到一个 DataTable 里再和DropDownList 关联
首先我用你的这些代码片段简单测试了,它可以正常工作。
其次,你给出的错误信息与代码片段有出入,错误信息是dropDownList1 , 而代码是dropDownList3 和 dropDownList4,我想这边是不是有些什么定义上的问题。如果不是的话,你可以发布一下dropDownList1 的数据填充相关代码。