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

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

    铺地毯 题目描述 为了准备一个独特的颁奖典礼,组织者在会场的一片矩形区域(可看做是平面直角坐标系的第一象限)铺上一些矩形地毯.一共有 n 张地毯,编号从 1 到n .现在将这些地毯按照编号从小到大的顺 ...

  2. yum install tree 出错primary.sqlite.bz2: [Errno -1] Metadata file does not match checks 解决办法

    Loaded plugins: fastestmirrorLoading mirror speeds from cached hostfilehttp://ftp.sjtu.edu.cn/centos ...

  3. Servlet表单数据处理

    以下内容引用自http://wiki.jikexueyuan.com/project/servlet/form-data.html: 当需要从浏览器到Web服务器传递一些信息并最终传回到后台程序时,一 ...

  4. 加上mvc:resources后controller访问404

    之前因为静态资源访问,404,于是加上了类似的代码 <mvc:resources location="/resources/" mapping="/resource ...

  5. muduo定时器、多线程模型及epoll的封装

    timerfd是Linux为用户程序提供的一个定时器接口,这个接口基于文件描述符. clock_gettime函数可以获取系统时钟,精确到纳秒.需要在编译时指定库:-lrt.可以获取两种类型时间: C ...

  6. 条款十七: 在operator=中检查给自己赋值的情况

    在赋值运算符中要特别注意可能出现别名的情况,其理由基于两点.其中之一是效率.如果可以在赋值运算符函数体的首部检测到是给自己赋值,就可以立即返回,从而可以节省大量的工作,否则必须去实现整个赋值操作. 另 ...

  7. How to enable Google Play App Signing

    how to enable google play app signing  ------------------------------------------------------------- ...

  8. Lightoj 1027 - A Dangerous Maze 【期望】

    1027 - A Dangerous Maze PDF (English) Statistics Forum Time Limit: 2 second(s) Memory Limit: 32 MB Y ...

  9. vux 全局使用 loading / toast / alert

    1.入口文件 main.js import { LoadingPlugin, ToastPlugin, AlertPlugin } from 'vux' Vue.use(LoadingPlugin); ...

  10. 图像处理之基础---基于opencv的灰度图像微分

    argv分别为,可执行文件名.读入的原始图像.输出原始图像的灰度值.输出原始图像灰度值沿x轴方向的一阶微分.输出原始图像灰度值沿x轴方向的二阶微分. #include #include #includ ...