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

思路:一次性查询出所需的记录(查询数据库的操作不宜写到 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
}

最终效果如下:

ASP.NET GridView 控件绑定 CheckBoxList的更多相关文章

  1. 在aspx页动态加载ascx页面内容,给GridView控件绑定数据

    在aspx页动态加载ascx页面内容 //加载ascx页面内容Control c1 = this.Page.LoadControl("WebUserControl1.ascx"); ...

  2. asp.net GridView控件的列属性

    BoundField 默认的数据绑定类型,通常用于显示普通文本 CheckBoxField 显示布尔类型的数据.绑定数据为TRUE时,复选框数据绑定列为选中状态:绑定数据为FALSE时,则显示未选中状 ...

  3. Asp.net GridView控件使用纪要

    1:数据绑定 GridView 支持数据绑定的数据源格式比较多,例如可以使用ObjectDataSource绑定数据源, Dataset,datatable,List<T>等 2:列绑定 ...

  4. ASP.net gridview控件RowEditing,RowUpdating,RowDeleting,RowCancelingEdit事件的触发

    一.说明 在gridview中删除和更新行是常用的操作,RowEditing,RowUpdating,RowDeleting,RowCancelingEdit等事件是删除更新对应的事件.如果想要使用自 ...

  5. asp.net TreeView控件绑定数据库显示信息

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

  6. 获取Asp.net GridView控件当中总的记录数量

    问题: 解决方案: SqlDataSource 或 AccessDataSource的selected事件的e.AffectedRows为查询操作返回的数据数目.(这个是在gridview分页情况下采 ...

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

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

  8. 初始ASP.NET数据控件GridView

    使用GridView控件绑定数据源 GridView控件个人认为就是数据表格控件,它以表格的形式显示数据源中的数据.每列表示一个字段,每行表示一条记录.     GridView控件支持在页面有一下功 ...

  9. Repeater, DataList, 和GridView控件的区别

    http://blog.sina.com.cn/s/blog_646dc75c0100h5p6.html http://www.cnblogs.com/phone/archive/2010/09/15 ...

随机推荐

  1. Thinkphp5.0 的实践一

    Thinkphp5.0 的实践一 tp5.0默认没有__SELF__,需要定义, define('__SELF__',strip_tags($_SERVER['REQUEST_URI'])); tp5 ...

  2. 洛谷——P1062 数列

    洛谷——P1062 数列 题目描述 给定一个正整数k(3≤k≤15),把所有k的方幂及所有有限个互不相等的k的方幂之和构成一个递增的序列,例如,当k=3时,这个序列是: 1,3,4,9,10,12,1 ...

  3. Evaluate Reverse Polish Notation(逆波兰式)

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  4. Java电商项目-6.实现门户首页数据展示_Redis数据缓存

    目录 项目的Github地址 需求介绍 搭建Redis集群环境 下面先描述单机版redis的安装 下面将进行Redis3主3从集群环境搭建 基于SOA架构, 创建门户ashop-portal-web门 ...

  5. 分享最近抽空写的一个代码生成器,集成EasyDBUtility数据库访问帮助类

    一直想写一个自己的代码生成器,但是因为工作事情多,一直搁置下来,最近下决心终于利用下班时间写完了,现在分享给有需要的朋友,代码生成器集成EasyDBUtility数据库访问帮助类,暂时只支持sqlse ...

  6. git的配置文件

    转载:https://cnbin.github.io/blog/2015/06/19/git-config-ming-ling-cha-kan-pei-zhi-wen-jian/ Git Config ...

  7. Websphere优化 (四个方面)举例

    Websphere优化 一.简单介绍 环境 名称 版本号 server操作系统 Centos 5.6 应用server操作系统 Windows 7 Websphere版本号 WAS 7.0 数据库 O ...

  8. C#.NET 无法直接启动带有类库输出类型的项目怎么办

    我把Driver.cs文件去掉了一行注释,发现报错   右击这个解决方案,选择属性,然后再启动项目中改成MySample    

  9. Linux Shell參数扩展(Parameter Expansion)

    本文主要參考:http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02 其它资料:ht ...

  10. vmstat输出项解释

    输出项的解释例如以下: procs * r列表示执行和等待cpu时间片段的进程数,这个值假设长期大约系统cpu个数.说明cpu不足 * b列表示在等待资源的进程数.比方正在等待IO或者内存交换等等 m ...