ASP.NET GridView 控件绑定 CheckBoxList
需求:设计这样一个页面,在页面上可以自由选择和展示各省份下城市?
思路:一次性查询出所需的记录(查询数据库的操作不宜写到 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的更多相关文章
- 在aspx页动态加载ascx页面内容,给GridView控件绑定数据
在aspx页动态加载ascx页面内容 //加载ascx页面内容Control c1 = this.Page.LoadControl("WebUserControl1.ascx"); ...
- asp.net GridView控件的列属性
BoundField 默认的数据绑定类型,通常用于显示普通文本 CheckBoxField 显示布尔类型的数据.绑定数据为TRUE时,复选框数据绑定列为选中状态:绑定数据为FALSE时,则显示未选中状 ...
- Asp.net GridView控件使用纪要
1:数据绑定 GridView 支持数据绑定的数据源格式比较多,例如可以使用ObjectDataSource绑定数据源, Dataset,datatable,List<T>等 2:列绑定 ...
- ASP.net gridview控件RowEditing,RowUpdating,RowDeleting,RowCancelingEdit事件的触发
一.说明 在gridview中删除和更新行是常用的操作,RowEditing,RowUpdating,RowDeleting,RowCancelingEdit等事件是删除更新对应的事件.如果想要使用自 ...
- asp.net TreeView控件绑定数据库显示信息
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
- 获取Asp.net GridView控件当中总的记录数量
问题: 解决方案: SqlDataSource 或 AccessDataSource的selected事件的e.AffectedRows为查询操作返回的数据数目.(这个是在gridview分页情况下采 ...
- asp.net GridView控件中诗选全选和全不选功能
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
- 初始ASP.NET数据控件GridView
使用GridView控件绑定数据源 GridView控件个人认为就是数据表格控件,它以表格的形式显示数据源中的数据.每列表示一个字段,每行表示一条记录. GridView控件支持在页面有一下功 ...
- Repeater, DataList, 和GridView控件的区别
http://blog.sina.com.cn/s/blog_646dc75c0100h5p6.html http://www.cnblogs.com/phone/archive/2010/09/15 ...
随机推荐
- codevs 1378 选课
题目描述 Description 学校实行学分制.每门的必修课都有固定的学分,同时还必须获得相应的选修课程学分.学校开设了N(N<300)门的选修课程,每个学生可选课程的数量M是给定的.学生选修 ...
- iOS 数据库操作崩溃提示“ int rc = sqlite3_step([_statement statement]);”或者提示“ rc = sqlite3_step(pStmt);”
数据库崩溃崩溃提示“ int rc = sqlite3_step([_statement statement]);”或者提示“ rc = sqlite3_step(pStmt);”的时候,可 ...
- hiho一下 第五十周 (求欧拉路径)
http://hihocoder.com/contest/hiho50/problem/1 这题有重边,所以邻接矩阵用来统计节点u,v之间有多少条边相连,并且用另外一个数组统计每个节点的入度. 然后查 ...
- 转 POJ分类
OJ上的一些水题(可用来练手和增加自信) (poj3299,poj2159,poj2739,poj1083,poj2262,poj1503,poj3006,poj2255,poj3094)初期: 一. ...
- Redis2019年3.22
redis缓存技术学习 一. redis基础配置 1. redis简介 1.1 redis 是c语言编写的一个缓存服务器, 是一个内存版本的nosql非关系型数据,大概11w/s访问处理. 数据都在本 ...
- spring依赖注入中获取JavaBean
一.这个接口有什么用? 当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean.换句话说,就是这个类可以 ...
- rsyslog trouble shooting
openstack,swift的log不输出了.trouble shooting过程 , 发现我们的程序 /var/log/swift/proxy.log等总是不输出log. 因为log rsyslo ...
- Google Chrome Developer Tools
原文:https://www.oschina.net/p/chromedevtools Google发布了Google Chrome Developer Tools,这是一系列面向Chrome开发者的 ...
- ubuntu语言设置成汉语
打开设置system setting,进入语言支持,有语言和地区格式.下载须要的语言并应用到整个系统. 按说明来就可以 这样的方法使得部分英语变为汉语.
- 改动ScrollView的滑动速度和解决ScrollView与ViewPager的冲突
话不多说,非常easy,能够从凝视中知道做法,直接上代码: 1.改动ScrollView的滑动速度: public class MyHorizontalScrollView extends Horiz ...