- 小弟在博客园驻园不久,初来咋到;将最近写的小程序附上,希望各位大牛们吐槽;激发对程序员围观的童鞋们,赶紧加入IT行业,如果你在上海那简称就是SHIT,哈哈题外话,以下开始切入正题:
坐公交车是旁边偶遇一小朋友,对我天朝区域不甚了解,为了偶的下一代不走回头路,激发爱国热情,故写下以下代码:
需求:
- 读取本地数据库(文本、Access);
- 根据省、市、县数据库切换,显示子级、父级;
以下是成形图:
实现步骤:
- 编写SqlHelper类(主要解决查询操作),代码如下
private static readonly string accessConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Directory.GetCurrentDirectory() + (@"\Areafull.accdb"); /// <summary> /// 查询access数据,返回table /// </summary> /// <param name="sql">执行sql</param> /// <param name="parameters">查询参数</param> /// <returns></returns> public static DataTable ExecuteAccessDateTable(string sql, params SqlParameter[] parameters) { using (OleDbConnection cnn = new OleDbConnection(accessConn)) { cnn.Open(); using (OleDbCommand cmd = cnn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); OleDbDataReader apter = cmd.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(apter); return dt; } } }
2.界面设计
三个ListBox控件分别放入,省,市,县
/// <summary> /// 初始化加载省数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Window_Loaded(object sender, RoutedEventArgs e) { DataTable table = SqlHelper.ExecuteAccessDateTable("select * from areafull where AreaPid=‘0‘"); SlB.ItemsSource = GetAreas(table);//省份绑定 } /// <summary> /// 省数据选择 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SlB_SelectionChanged(object sender, SelectionChangedEventArgs e) { Area areaRow = (Area)SlB.SelectedItem; DataTable table = SqlHelper.ExecuteDateTable("select * from areafull where AreaPid=@AreaPid", new SqlParameter("@AreaPid", areaRow.AreaId)); SJBX.ItemsSource = GetAreas(table); } /// <summary> /// 市级数据选择 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SJBX_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (SJBX.SelectedItem != null) { Area areaRow = (Area)SJBX.SelectedItem; DataTable table = SqlHelper.ExecuteDateTable("select * from areafull where AreaPid=@AreaPid", new SqlParameter("@AreaPid", areaRow.AreaId)); XJBX.ItemsSource = GetAreas(table); } else { XJBX.ItemsSource = null; } } /// <summary> /// 数据转换对象 /// </summary> /// <param name="table"></param> /// <returns></returns> private List<Area> GetAreas(DataTable table) { List<Area> lst = new List<Area>(); foreach (DataRow item in table.Rows) { Area are = new Area(); are.AreaId = Convert.ToInt32(item["Areaid"]); are.AreaName = item["AreaName"].ToString(); are.AreaPid = Convert.ToInt32(item["AreaPid"]); lst.Add(are); } return lst; }
总结:
- 程序中主要用到数据转换对象的思想(Data——》Object);
- Ato.net本身提供的数据访问类;
需要数据库及源码的直接回复我
如在过程中提示未注册驱动,请到以下地址:下载安装即可