我測試,我得到了作爲一個例子來嘗試的代碼,但我得到的錯誤C#錯誤:對象引用不設置到對象的實例,但不知道如何讓空
Object reference not set to an instance of an object
我沒有看到這個錯誤的含義,我發現它在對象引用NULL時發生。在這條線上
string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
唯一的問題是我不知道如何正在生成NULL,因此無法修復產生
錯誤。
我該如何解決這個問題?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select CountryId, CountryName from Countries";
BindDropDownList(ddlCountries, query, "CountryName", "CountryId", "Select Country");
ddlStates.Enabled = false;
ddlCities.Enabled = false;
ddlStates.Items.Insert(0, new ListItem("Select State", "0"));
ddlCities.Items.Insert(0, new ListItem("Select City", "0"));
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
con.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
它可能無法找到在一個「ConString」鍵文件。 – LarsTech
你的web.config中有'ConString'嗎? –
'ConfigurationManager.ConnectionStrings [「ConString」]'key'很可能在配置文件中丟失 –