第六讲 ASP.NET应用:DataGrid使用最佳实践

*摘要
-列表控件概述
-列表控件是如何工作的
-DataGrid基本使用
-DataGrid常用的使用技巧
-DataGrid其他使用技巧

*列表控件概述
.能够取得数据集,并自动遍历它们
.比其他控件要复杂的多
.这些控件把绑定到它们的数据通过HTML表现出来
.常用作其他实际显示数据的控件的容器
.功能强大、较复杂
.用于以下应用:报表、购物推车、产品列表、查询结果显示、导航菜单

*列表控件是如何工作的
-DataSource属性: 最简单地讲,就是一组相同特征的对象或者一个相同对象的集合
-Items集合 :每一个列表绑定控件都有一个Items集合,集合中的每一个Item是DataSource所指定的一个对象

*数据绑定
-列表绑定控件基于ASP.NET框架,需要你明确地进行数据绑定。这就意味着:只有当DataBind方法被调用时,才真正

需要轮询其DataSource 所代表的数据。
-当DataBind方法被调用时,列表绑定控件将轮询DataSource,创建Items集合,并从DataSource取回数据,以初始化

Items集合

*DataGrid基本使用
-DataGrid控件可用于创建各种样式的表格。它还支持对项目的选择和操作,是最复杂、功能最强大!
-DataGrid的AutoGenerateColumns属性缺省是True。当AutoGenerateColumns为True 时,DataGrid将检查其数据源和

其对象映射,并为每一个共有属性或者字段创建一个列。
-每一个自动产生的列称为一个BoundColumn(绑定列)。绑定列根据其数据表对应列的数据类型,自动将其转化为一

个字符串,显示在表格的一个单元中。

*DataGrid列的类型包括:
绑定列
模板列
编辑和删除列
*事件
编辑
取消
更新
删除
分页

*DataGrid常用的使用技巧
.日期的显示
d  将日显示为不带前导零的数字(如 1)。
dd  将日显示为带前导零的数字(如 01)。
ddd  将日显示为缩写形式(例如 Sun)。
dddd  将日显示为全名(例如 Sunday)。
M  将月份显示为不带前导零的数字(如一月表示为 1)
MM  将月份显示为带前导零的数字(例如 01/12/01)。
MMM  将月份显示为缩写形式(例如 Jan)。
MMMM  将月份显示为完整月份名(例如 January)。
h  使用12 小时制将小时显示为不带前导零的数字(例如 1:15:15 PM)。
hh  使用 12 小时制将小时显示为带前导零的数字(例如 01:15:15 PM)。
H  使用 24 小时制将小时显示为不带前导零的数字(例如 1:15:15)。
HH  使用 24 小时制将小时显示为带前导零的数字(例如 01:15:15)。
m  将分钟显示为不带前导零的数字(例如 12:1:15)。
mm  将分钟显示为带前导零的数字(例如 12:01:15)。
s  将秒显示为不带前导零的数字(例如 12:15:5)。
ss  将秒显示为带前导零的数字(例如 12:15:05)。
y  将年份 (0-9) 显示为不带前导零的数字。
yy  以带前导零的两位数字格式显示年份(如果适用)。
yyy  以三位数字格式显示年份。
yyyy  以四位数字格式显示年份。
<asp:BoundColumn DataField="Birthday" HeaderText="生日" DataFormatString="{0:yyyy-M-d}"></asp:BoundColumn>

.传递DataGrid中的值
<asp:HyperLinkColumn Text="点击查看" DataNavigateUrlField="StudentID" DataNavigateUrlFormatString="Show.aspx?ID={0}" DataTextField="StudentName" HeaderText="详细信息"></asp:HyperLinkColumn>

show.aspx.cs中的代码
Response.Write("您选择的学生ID是:"+Request.QueryString["ID"]);

.在DataGrid里添加确认删除的对话框
-第一种方法
1、在DataGrid_ItemCreated()事件中加myDeleteButton.Attributes.Add(...)属性(客户端脚本)
private void dgShow_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
 switch(e.Item.ItemType)
 {
  case ListItemType.Item:
  case ListItemType.EditItem:
  case ListItemType.AlternatingItem:
  Button    myDeleteButton = (Button)e.Item.FindControl("btnDelete");
  myDeleteButton.Text = "删除此行";
  myDeleteButton.Attributes.Add("onclick", "return confirm('您真的要删除第 " + e.Item.ItemIndex.ToString() + " 行吗?');");
  break;
 }
}
2、再在DataGrid_ItemCommand(...)事件中,写服务器端功能代码
private void dgShow_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
  if(e.CommandName=="UserDelete")
  dgShow_DeleteCommand(source,e);
}

-第二种方法
1、直接在模板列中添加客户端脚本
<asp:TemplateField HeaderText="删除" ShowHeader="False">
 <ItemTemplate>
   <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"onclientclick="return confirm(&quot;删除将不能恢复,确认要删除吗?&quot;)" Text="删除" CommandName="Delete">
   </asp:LinkButton>
 </ItemTemplate>
</asp:TemplateField>
2、服务器端代码同上。

.格式化DataGrid :将数据原中的0,1值转换成实际的文字
<asp:TemplateColumn HeaderText="性别模板列">
 <ItemTemplate>
  <asp:RadioButton id=RadioButton2 runat="server" Text="男" Checked='<%# DataBinder.Eval(Container, "DataItem.Sex") %>' Enabled="False"></asp:RadioButton>
  <asp:RadioButton id=RadioButton1 runat="server" Text="女" Checked='<%# !(bool)DataBinder.Eval(Container, "DataItem.Sex") %>' Enabled="False"></asp:RadioButton>
 </ItemTemplate>
 <EditItemTemplate>
  <asp:RadioButton id=cbSex runat="server" Text="男" Checked='<%# DataBinder.Eval(Container, "DataItem.Sex") %>' GroupName="Sex"></asp:RadioButton>
  <asp:RadioButton id=RadioButton4 runat="server" Text="女" Checked='<%# !(bool)DataBinder.Eval(Container, "DataItem.Sex") %>' GroupName="Sex"></asp:RadioButton>
 </EditItemTemplate>
</asp:TemplateColumn>

.在DataGrid中选择,确认,删除多行复选框列表
1、添加一个“选择模板列”。
<asp:TemplateColumn HeaderText="选择">
 <HeaderTemplate>
  <asp:CheckBox id="cbAll" runat="server" OnCheckedChanged="CheckAll" Text="全选" AutoPostBack="True"></asp:CheckBox>
 </HeaderTemplate>
 <ItemTemplate>
  <asp:CheckBox id="cbSelect" runat="server" AutoPostBack="True"></asp:CheckBox>
 </ItemTemplate>
</asp:TemplateColumn>
2、在CheckAll事件中添加代码
public void CheckAll(object sender, System.EventArgs e)
{
 CheckBox cbAll = (CheckBox)sender;
 if(cbAll.Text=="全选")
 {
  foreach(DataGridItem dgi in dgShow.Items)
  {
   CheckBox cb = (CheckBox)dgi.FindControl("cbSelect");
   cb.Checked = cbAll.Checked;
  }
 }
}

.利用dropdownlist下拉列表框,显示数据库表中的某个字段
1、添加模板列
<asp:TemplateColumn HeaderText="性别模板列">
 <ItemTemplate>
  <asp:DropDownList id="ddlSexI" runat="server" Enabled="False">
   <asp:ListItem Value="1">男</asp:ListItem>
   <asp:ListItem Value="0">女</asp:ListItem>
  </asp:DropDownList>
 </ItemTemplate>
 <EditItemTemplate>
  <asp:DropDownList id="ddlSexE" runat="server">
   <asp:ListItem Value="1">男</asp:ListItem>
   <asp:ListItem Value="0">女</asp:ListItem>
  </asp:DropDownList>
 </EditItemTemplate>
</asp:TemplateColumn>
2、数据绑定时,额外的绑定代码
private void BindData()
{
 string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
 SqlConnection con = new SqlConnection(strCon);
 SqlDataAdapter da = new SqlDataAdapter("Select * from tbStudentinfo",con);
 DataSet ds = new DataSet();
 da.Fill(ds,"studentinfo");
 dgShow.DataSource = ds.Tables["studentinfo"].DefaultView;
 dgShow.DataBind();
 foreach(DataGridItem dgi in dgShow.Items)
{
 //以下绑定非编辑状态下拉列表
 DropDownList ddI = (DropDownList)dgi.FindControl("ddlSexI");
 if(ddI!=null)
 {
  bool bSex = (bool)ds.Tables["studentinfo"].Rows[dgi.ItemIndex]["Sex"];
  if(bSex)
   ddI.SelectedIndex = 0;
  else
   ddI.SelectedIndex = 1;
 }
  //以下绑定编辑状态下拉列表
 DropDownList ddE = (DropDownList)dgi.FindControl("ddlSexE");
 if(ddE!=null)
{
 bool bSex = (bool)ds.Tables["studentinfo"].Rows[dgi.ItemIndex]["Sex"];
 if(bSex)
  ddE.SelectedIndex = 0;
 else
  ddE.SelectedIndex = 1;
}    
}   
}

.取得Datagrid里的checkbox返回值
string strSex = ((CheckBox)(e.Item.Cells[3].FindControl("cbSex"))).Checked?"1":"0";

.datagrid中加入统计值
1、显示页脚:ShowFooter="True"
2、数据绑定时额外添加绑定代码
private void BindData()
{
 string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
 SqlConnection con = new SqlConnection(strCon);
 SqlDataAdapter da = new SqlDataAdapter("Select * from tbStudentinfo",con);
 DataSet ds = new DataSet();
 da.Fill(ds,"studentinfo");
 dgShow.DataSource = ds.Tables["studentinfo"].DefaultView;
 dgShow.DataBind();
 //以下作分数和的统计
 int count=0;
 for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
 {
  count += int.Parse(ds.Tables[0].Rows[i]["Score"].ToString());
 }
 int nAv = count/ds.Tables[0].Rows.Count;
 foreach(DataGridItem dgi in dgShow.Controls[0].Controls)
 {
  if (dgi.ItemType == ListItemType.Footer)
   dgi.Cells[6].Text = "平均:"+nAv.ToString();
 }
}

.DataGrid_UpdateCommand(...)事件这么写
private void dgShow_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
  string strStudentID = e.Item.Cells[0].Text;//处于非编辑状态
  string strName = ((TextBox)(e.Item.Cells[1].Controls[0])).Text;//处于编辑状态
  string strPass =((TextBox)(e.Item.Cells[2].Controls[0])).Text;
  string strSex = ((CheckBox)(e.Item.Cells[3].FindControl("cbSex"))).Checked?"1":"0";
  string strBirthday =((TextBox)(e.Item.Cells[4].Controls[0])).Text;
  string strEmail =((TextBox)(e.Item.Cells[5].Controls[0])).Text;
  string strSql = "update tbStudentinfo set StudentName='"+strName+"',StudentPass='"+strPass+"'";
  strSql +=",Sex="+strSex+",Birthday='"+strBirthday+"',Email='"+strEmail+"' where studentid="+strStudentID+"";
  ExecuteSql(strSql);
  dgShow.EditItemIndex = -1;
  BindData();
}


*DataGrid其他使用技巧
.如何用程序隐藏和显示DataGrid中的一列
dgShow.Columns[0].Visible = false;

.如何控制datagrid里编辑功能出现的TextBox的宽度?
在DataGrid_ItemDataBound(...)事件中写代码
例如
private void dgShow_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
 if (e.Item.ItemType == ListItemType.EditItem)
 {
  for (int i=0;i<e.Item.Cells.Count;i++)
  {
   if(e.Item.Cells[i].Controls.Count>0)
   {
    try
    {
     TextBox t =(TextBox)e.Item.Cells[i].Controls[0];
     t.Width=130;
    }
    catch(Exception ee)
    {}
   }
  }
 }
}

.datagrid只显示dataset中多列数据中的一列
DataGrid的AutoGenerateColumns属性设为False,自己加绑定列。


.DataGrid 中的数据导出到 Microsoft Excel
private void BindData()
{
 string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
 SqlConnection con = new SqlConnection(strCon);
 SqlDataAdapter da = new SqlDataAdapter("Select * from tbStudentinfo",con);
 DataSet ds = new DataSet();
 da.Fill(ds,"studentinfo");
 dgShow.DataSource = ds.Tables["studentinfo"].DefaultView;
 dgShow.DataBind();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
 //
 // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
 //
 InitializeComponent();
 base.OnInit(e);
}
  
 /// <summary>
 /// 设计器支持所需的方法 - 不要使用代码编辑器修改
 /// 此方法的内容。
 /// </summary>
private void InitializeComponent()
{   
}
#endregion

protected void btnMIME_Click(object sender, System.EventArgs e)
{
 Response.ContentType = "application/vnd.ms-excel";
 Response.Charset = "";
 this.EnableViewState = false;
 System.IO.StringWriter sw = new System.IO.StringWriter();
 System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
 int nCur = dgShow.CurrentPageIndex;
 int nSize = dgShow.PageSize;
   
 dgShow.AllowPaging = false;
 BindData();
    
 dgShow.Columns[7].Visible =false;
 dgShow.RenderControl(hw);
 dgShow.Columns[7].Visible =true;
   
 //以下恢复分页
 dgShow.AllowPaging = true;
 dgShow.CurrentPageIndex = nCur;
 dgShow.PageSize = nSize;
 BindData();
 Response.Write(sw.ToString());
 Response.End();
}

 

 

转载于:https://www.cnblogs.com/iceberg2008/archive/2009/03/17/1413897.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值