Ado.Net实现简易(省、市、县)三级联动查询,还附加Access数据
坐公交车是旁边偶遇一小朋友,对我天朝区域不甚了解,为了偶的下一代不走回头路,激发爱国热情,故写下以下代码:
需求:
读取本地数据库(文本、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本身提供的数据访问类;
上一篇: 西红柿炒鸡蛋的制作方式
下一篇: 鸡蛋汤的做法及优点