需求:设计这样一个页面,在页面上可以自由选择和展示各省份下城市?

思路:一次性查询出所需的记录(查询数据库的操作不宜写到 C# 代码的循环语句中),并保存到全局变量中,之后根据条件过滤出需要的。可以在 WebForm 页面中,添加相应的 ASP.NET 服务器控件:GridView 和 CheckBoxList 来实现,只需绑定相应的数据即可。

前台页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ProvinceCityConfig.aspx.cs" Inherits="ProvinceCityConfig"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>选择各省份下的城市</title>
<link rel="stylesheet" type="text/css" href="../css/basic.css" />
<script src="../jQuery/jquery-1.5.1.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(function () {
//表格隔行变色
$("table.queryList_font12 th").css("background", "#f2f2f2");
$("table.queryList_font12 .item_td_center:even").css("background", "#f0fafa");
$("table.queryList_font12 .item_td:even").css("background", "#f0fafa");
});
</script>
</head>
<body>
<form id="form1" runat="server">
<dl class="si_info">
<dd class="marginleft24">
<dl>
<dt>请选择各省份下的城市</dt>
</dl>
</dd>
</dl>
<div class="content">
<div style="border: 1px solid silver; max-height: 400px; overflow-y: auto; overflow-x: hidden;" id="divList" runat="server">
<asp:GridView ID="gvList" runat="server" Width="100%" Height="100%" DataKeyNames="PROVINCE_SEQ"
OnRowDataBound="gvItem_RowCommand" CssClass="queryList_font12 mytable" BorderWidth="1px" AutoGenerateColumns="False">
<HeaderStyle CssClass="gv_header" />
<Columns>
<asp:TemplateField HeaderText="省份">
<HeaderStyle CssClass="header_th_center" Wrap="False" Width="12%" Font-Size="12px" />
<ItemStyle CssClass="item_td_center" Width="15%" />
<ItemTemplate>
<asp:Label ID="province" runat="server" ToolTip='<%#Eval("PROVINCE_SEQ") %>'
Text='<%# Eval("PROVINCE_CODE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="城市">
<HeaderStyle CssClass="header_th_center" Wrap="False" Width="85%" Font-Size="12px" />
<ItemStyle CssClass="item_td" Wrap="False" Width="85%" />
<ItemTemplate>
<asp:CheckBoxList ID="city" runat="server" RepeatLayout="Table" RepeatDirection="Horizontal" RepeatColumns="10" ></asp:CheckBoxList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate />
<PagerSettings Visible="False" />
<EmptyDataRowStyle HorizontalAlign="Center" />
</asp:GridView>
</div>
<table class="inputlist_table" border="0" cellspacing="0" cellpadding="0" style="width: 100%;">
<tr>
<td align="center">
<asp:Button ID="btnSave" runat="server" Text="保存"OnClick="btnSave_Click" CssClass="ok" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

后台代码文件:

using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common; public partial class ProvinceCityConfig : PageBase
{
#region Fields private ProvinceCityRelation provinceCitySevice = new ProvinceCityRelation();
protected log4net.ILog log = log4net.LogManager.GetLogger("ExceptionLogger");
private DataSet allCityCache = new DataSet();
private DataSet selectCityCache = new DataSet(); #endregion Fields #region Events protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -;
try
{
OpUserEntity opUser = new OpUserEntity();
opUser.userID = this.CurrentUser.Username;
opUser.compSEQ = this.CurrentUser.CompanySeq;
buscity.opUser = opUser; if (!IsPostBack)
{
ShowData();
}
}
catch (Exception ex)
{
log.Error("[ProvinceCityConfig::Page_Load]" + ex);
MessageBox.Show(this, "页面加载失败,请重试或联系客服人员!");
}
} /// <summary>
/// 保存省份与城市的对应关系
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnSave_Click(object sender, EventArgs e)
{
DbTransaction tran = SqlHelper.OpenTransaction();
List<ProvinceCityRelationDto> list = new List<ProvinceCityRelationDto>(); //依次获取DataGridView中各控件的值,并添加到list中
for (int i = ; i < gvList.Rows.Count; i++)
{
string Province = (gvList.Rows[i].Cells[].Controls[] as Label).ToolTip;
CheckBoxList cityList = gvList.Rows[i].Cells[].Controls[] as CheckBoxList; //每家省份是否选中了一个城市
bool hasOne = false; for (int j = ; j < cityList.Items.Count; j++)
{
if (cityList.Items[j].Selected)
{
hasOne = true;
ProvinceCityRelationDto dto = new ProvinceCityRelationDto();
decimal configSeq = ;
decimal citySeq = ;
decimal.TryParse(Province, out configSeq);
decimal.TryParse(cityList.Items[j].Value, out citySeq);
dto.BusinessConfigSeq = configSeq;
dto.cityDictSeq = citySeq;
list.Add(dto);
}
} if (!hasOne)
{
MessageBox.Show(this, "每个省份至少选择一个城市才能保存");
return;
}
} //提交保存
SuperResult result = provinceCityRelation.Save(list, tran);
if (result.opResult == ResultValue.Succ)
{
MessageBox.Show(this, "保存成功");
tran.Commit();
ShowData();
}
else
{
MessageBox.Show(this, "系统异常,请联系客服人员");
tran.Rollback();
ShowData();
}
} protected void gvItem_RowCommand(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBoxList cityList = (CheckBoxList)e.Row.FindControl("city");
if (cityList != null)
{
string ProvinceSeq = gvList.DataKeys[e.Row.RowIndex].Value.ToString(); cityList.DataSource = allcityCache.Tables[].DefaultView;
cityList.DataValueField = "CITY_SEQ";
cityList.DataTextField = "CITY_CODE";
cityList.DataBind(); if (!DataHelper.IsEmpty(selectCityCache))
{
//用DataSet一次性查询出所有记录,然后根据条件来过滤出所需要的数据
DataRow[] correctRows = selectCityCache.Tables[0].Select("PROVINCE_SEQ = " + ProvinceSeq, "CITY_CODE ASC");
foreach (DataRow row in correctRows)
{
//checkbox显示为“已选中”
if (cityList.Items.FindByValue(row["CITY_SEQ"].ToString()) != null)
{
cityList.Items.FindByValue(row["CITY_SEQ"].ToString()).Selected = true;
}
}
}
}
}
}
#endregion #region Methods /// <summary>
/// 查询相关的数据
/// 思路:先查出所有数据,然后根据条件筛选出所需信息
/// </summary>
private void ShowData()
{//查询所有的城市
string allCitySql = @"SELECT P.CITY_SEQ,P.CITY_CODE FROM CITY P WHERE P.STATUS =1 ORDER BY P.CITY_CODE ASC";
//结果保存到全局变量中
allCityCache = SqlHelper.ExecuteDataSet(allCitySql); //查询所有的省份和城市的匹配信息
if (!DataHelper.IsEmpty(allCityCache))
{
string selectCitySql = @"SELECT T.PROVINCE_SEQ,T.CITY_SEQ,P.CITY_CODE,P.STATUS
FROM PROVINCE_CITY_REF T LEFT JOIN CITYP P ON P.CITY_SEQ = T.CITY_SEQ
WHERE P.STATUS = 1";
DataSet selectCity = SqlHelper.ExecuteDataSet(selectCitySql); //结果保存到全局变量中
selectCityCache.Merge(selectCity);
//selectcityCache.Tables.Add(selectCity);
} //查询所有的省份,并绑定到gridview
string sqlProvince = @"SELECT B.PROVINCE_SEQ, B.PROVINCE_CODE FROM PROVINCE B WHERE B.STATUS = 1 ORDER BY B.PROVINCE_CODE ASC";
DataSet allProvince = SqlHelper.ExecuteDataSet(sqlProvince);
//绑定省份到gridview的第一列
gvList.DataSource = allProvince.Tables[];
gvList.DataBind(); //数据为空时,显示默认的表头
if (dsProvince.Tables[].Rows.Count <= )
{
BaseDataTool.AddTableTop(this.gvList);
}
} #endregion
}

最终效果如下:

GridView 控件中如何绑定 CheckBoxList的更多相关文章

  1. GridView控件中加自动排列序号

    GridView控件中加自动排列序号 为 Gridview 增加一个新的空白列,如下: <asp:BoundField  HeaderText="序号">    < ...

  2. GridView控件中插入自定义删除按钮并弹出确认框

    GridView控件中插入自定义删除按钮,要实现这个功能其实有多种方法,这里先记下我使用的方法,以后再添加其他方法. 一.实现步骤 1.在GridView中添加模板列(TemplateField). ...

  3. GridView控件中Checkbox实现单选

    在GridView控件中,第0列有放一个CheckBox控件,现想实现对CheckBox进行单选. 先看看效果: 在ASPX页面,可以这样做: 有一点注意的是需要使用OnRowCreated事件. 在 ...

  4. GridView内按钮Click获取记录主键值 在GridView控件中,每行记录内会放置一个铵钮,当用

    在GridView控件中,每行记录内会放置一个铵钮,当用户点击这个铵钮时,获取当笔记录的主键值.可看演示(是一个gif动画,重新播放尝试刷新网页): 实现这个功能,你需要为GridView控件设置Da ...

  5. GridView控件中的一些常见问题

    1. 无法获取模板列中的值,使用FindControl()方法无效: 给模板列中添加隐藏域,并给隐藏域绑定要获取的值,代码如下: <asp:HiddenField ID="hfIsFr ...

  6. Metro之GridView控件的使用-绑定不同的模板样式显示

    最终实现的效果如下: 添加MenuDataSource.cs,字段ImageStyle是用来标识套用的样式 public class MenuGroup { public string GroupTi ...

  7. 在Gridview控件中根据Field Name来取得对应列索引

    下面方法,只能在Gridview的BoundField进行操作,而在TemplateField模版中去找的话,就无能为力了,因TemplateField模版没有DataField属性.  public ...

  8. asp.net GridView控件中诗选全选和全不选功能

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  9. 027. asp.net中数据绑定控件之 GridView控件

    GridView控件支持下面的功能: 绑定至数据源控件, 如SqlDataSource 内置排序功能 内置更新和删除功能 内置分页功能 内置行选择功能 可以编程方式访问GridView对象模型以动态设 ...

随机推荐

  1. [SoapUI] SoapUI JDBC REST 连接 Netezza

    How to Connect to Server 1. Apply accounts that has permission to access Netezza system for host acc ...

  2. redis 配置应用(摘)

    Redis可以在没有配置文件的情况下通过内置的配置来启动,但是这种启动方式只适用于开发和测试. 合理的配置Redis的方式是提供一个Redis配置文件,这个文件通常叫做redis.conf. redi ...

  3. MongoDB:实体对象(javabean)转DBObject

    代码仅供练习(反射,泛型): package utils; import java.lang.reflect.Field; import com.mongodb.BasicDBObject; impo ...

  4. Caché数据库学习笔记(2)

    目录: 创建新类(表)(class文件)与创建routine(.mac  .inc) 在类里面添加函数(classmethod) Terminal的使用 ======================= ...

  5. 【转】从 ArcGIS for Desktop 发布地图服务

    原文链接:http://resources.arcgis.com/zh-CN/help/tutorials/01z300000007000000.htm 本教程的目的是将地图服务直接从 ArcGIS ...

  6. CSS Hack相关知识

    CSS Hack 1.由于不同厂商的浏览器,比如Internet Explorer,Safari,Chrome,Mozila Firefox等,或者是同一厂商的浏览器的不同版本,如IE6和IE7,对C ...

  7. C#窗体 WinForm 文件操作

    文件及文件夹操作 C/S:WinForm可以操作客户端文件 Client ServerB/S:浏览器服务 Brower Server 命名空间:using system .IO; 1. File类:文 ...

  8. 学习swift开源项目

    如果你是位iOS开发者,或者你正想进入该行业,那么Swift为你提供了一个绝佳的机会.Swift的设计非常优雅,较Obj-C更易于学习,当然也非常强大. 为了指导开发者使用Swift进行开发,苹果发布 ...

  9. JVM-并发-线程安全与锁优化

    线程安全与锁优化 1.线程安全 (1)当多个线程访问一个对象时,如果不考虑这些线程在执行时环境下的调度和交替执行,也不需要进行额外的同步,或者在调用方进行任何其他的协调操作,调用这个对象的行为都可以获 ...

  10. 开发者如何利用工具快速开发出完美APP

    文|移动互联网李建华 微信:ydhlwdyq 传统的个人开发者,要想开发出一个完美的APP要 经过以下几个过程:搭建开发环境,写代码,写统计系统,开发即将完成后,要购买服务器,然后把程序布置到服务器上 ...