数据绑定控件关系
BaseDataBoundControl DataBoundControl -- HierarchcalDataControl
HierarchcalDataControl Tree--Menu
DataBoundControl AdRotator---ListControl--CompositeDataBoundControl
ListControl DropDownList CheckBoxList RadioButtonList ListBox BulletList
CompositeDataBoundControl GridView---DetaisView---FormView
<2>GridView控件提供的所有字段类型
BoundField 表示数据绑定控件中作为文本显示的字段,属于应用最多的类型
CheckBoxField 表示数据绑定控件中以复选框显示的布尔型字段
HyperLinkField 表示在数据绑定中显示为超链接的字段
BottonField 表示一个字段,该字段显示为数据绑定中的按钮
CommandField 表示一个特殊字段,其中显示了用于在数据绑定控件中执行选择。删除。更新,删除
ImageField 表示在数据绑定控件中显示为图片的字段
TemplateField 表示在数据绑定控件中显示自定义内容的字段
<3>BoundField字段
属性:DataFormatString,可设置显示字段的格式 {0:C}格式为货币类型
注意,当HtmlCode属性设置为false DataFormatString才有效
<4> HyperLinkField字段
DataNaVigateUrlFields 绑定数据库字段,多个就用 , 分隔
DatanaVigateUrlFormatstring 超链接到的页面
DatanaVigateUrlFormatstring="default.aspx?name={0}&
address={1}&city={2}&state={3}"
DataNaVigateUrlFields="name,address,state,zip"
模板列 TemplateField字段
基本属性
ItemTemplate:偶数行的单元格
AlternatingItemTemplate:奇数行的单元格
EditItemTemplate:单击“编辑”按钮后,单元格的内容
HeaderTemplate:设置列头单元格
FooterTemplate:页脚单元格
DataKeyNames,存储网格绑定的数据表的主键
<13>命令按钮列
一个特殊字段,显示用于在数据绑定控件中执行选择,编辑,插入,删除的命令操作
自动生成命令,无须手写
对应数据源的增改查删方法
<14>为了避免用户无意中删除数据,需要在删除前以对话框的方式询问用户。
foreach(GridViewRow row in GridView1.Row)
{
LinkButton lb=row.Cells[0].Controls[0] as LinkButton;
lb.Attributes.Add("onclient","return confirm("delete ?");");
}
<15>取消删除
为了取消对某些条件的记录进行删除,需要在删除时取消删除过程,并提示用户
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) {
if (int.Parse(GridView1.Rows[e.RowIndex].Cells[1].Text) % 2 == 0) {
e.Cancel = true;
ClientScript.RegisterStartupScript(this.GetType(),"",
"<script>alert ('不能删除编号为偶数的记录!');</script>");
}
}
页眉模板——多选效果
<HeaderTemplate>
<input id="cbAll" type="checkbox" onclick="return cbAll_onclick()" />全选
</HeaderTemplate>
function cbAll_onclick()
{
var items = document.getElementsByTagName("input");
for(i=0; i<items.length;i++)
{
if(items[i].type=="checkbox")
{
items[i].checked = document.form1.cbAll.checked;
}
}
}
行模板——光棒效果
protected void gvDemo_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.bac kgroundColor='#6699ff'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor");
}
}
页脚模板——显示列汇总
n事件:RowDataBound
n行类型参数: e.Row.RowType
n行中某一列文本: e.Row.Cells[6].Text
int all;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow){
all +=int.Parse( e.Row.Cells[6].Text);
}
if (e.Row.RowType == DataControlRowType.Footer){
e.Row.Cells[6].Text = "库存总量:"+all;
}
}
<12> Eval和Bind
Eval 方法是只读方法:¨该方法采用数据字段的值作为参数并将其作为字符串返回。
¨当对表达式操作时候,必须用Eval
如<%# Eval("字段名").ToString( ).Trim( ) %>
<%# Eval("PublishDate", "{0:dd/MM/yyyy}") %>
Bind 方法支持读/写功能
可以检索数据绑定控件的值并将任何更改提交回数据库