本帖最后由 李玮 于 2012-6-18 10:56 编辑
我刚刚学到查询省市的那一课,在用配置文件储存 连接代码 时 改了名字 不叫app.config 叫apptt.config 为啥就报错啊 警告提示:未将对象引用设置到对象的实例。
然后,纠结了半天,看了半天视频 也没找到错误 最后 从新做了一次 把配置文件 命名为app.config 就正常运行了,然后改了名字还不行,难道是默认命名不用声明?
这是为什么啊? 下面是 那个选择省市的代码!!!!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace 省市查询
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string peizhi = ConfigurationManager.ConnectionStrings["peizhi"].ConnectionString;
using (SqlConnection conn = new SqlConnection(peizhi))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from promary";
using(SqlDataReader reader = cmd.ExecuteReader() )
{
while (reader.Read())
{
shengss item = new shengss();
item.Name=reader.GetString(reader.GetOrdinal("proname"));
item.Id = reader.GetInt32 (reader.GetOrdinal("proID"));
cmbsheng.Items.Add(item);
}
}
}
}
}
private void cmbsheng_SelectedIndexChanged(object sender, EventArgs e)
{
cmbshi.Items.Clear();
shengss item = (shengss)cmbsheng.SelectedItem;
int idx = item.Id;
// string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string peizhi = ConfigurationManager.ConnectionStrings["peizhi"].ConnectionString;
using (SqlConnection conn = new SqlConnection(peizhi))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select cityname from city where proid=@idx";
cmd.Parameters.Add(new SqlParameter("idx", idx));
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string cityname = reader.GetString(reader.GetOrdinal("cityname"));
cmbshi.Items.Add(cityname);
}
}
}
}
}
private void cmbshi_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
class shengss
{
string name;
int id;
public int Id
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
}
}
|