DATAGRID经典技巧(经典而且容易,好东西来的)

DataGrid/DataList在ASP.NET中的重要性,想必就不用我再强调了,凡显示Table类型的数据,大多会使用这两个控件(当然,如果谁还像ASP那样写ASP.NET,那我也没有办法),所以,每个人可能都有自己的领悟,这篇文章,算是抛砖引玉,为大家做个铺垫。

一、方法
1、DataBind
很简单、最常用的方法。绑定数据用。需要注意的只有一点:执行了这个方法后,DataGrid(由于DataGrid和DataList极为相似,所以下面的介绍虽然是针对DataGrid,但与DataList也相差不远)里面所有的显示绑定数据的控件,都会显示DataSource里的数据,其余控件也将初始化成.aspx里设计的状态。


二、属性
1、DataSource
有DataBind的地方,就应该有DataSource。如果没有指定DataSource而执行DataBind,那DataGrid将什么也不会显示。
DataSource一般是DataSet、DataTable或者DataView。当然也可以绑定DataReader或者其他实现IEnumerable的类。

2、DataKeyField,DataKeys
当你在DataGrid中定位一行之后,肯定想知道这行在数据表里的位置,至少有五种方法可以做到这一点,设置DataGrid的DataKeyField就是这几种方法之一。
DataKeyField一般设置为数据表的Unique字段(否则就没意义了),通过DataKey可以得到这一行对应的关键字段的值。
DataKeys是DataKey的集合,通过行的索引来读取相应行的DataKey。

3、EditItemIndex,SelectedIndex,CurrentPageIndex,SelectedItem
这些属性都很好理解,看名字就知道是什么意思,需要注意的是,设置了EditItemIndex或者CurrentPageIndex后需要重新执行DataBind方法(当然,前面提到过,还需要设置DataSource)。

4、Columns
没什么好解释的,Columns就是Columns,列的集合,可以设置列的属性,包括Visible、HeaderText、FooterText、SortExpression等。
严重注意:自动生成的列,是不包含在Columns中的。只有在.aspx中显示声明的列和在代码中添加的列才会被包含在其中。

5、Items
俗话说,最后的都是最重要的,把Items作为最后一个属性来介绍,正式基于这样的理由。
Items是DataGridItem的集合,可以遍历当前DataGrid中显示数据的DataGridItem。
5.1、DataGridItem
每一个DataGridItem就是DataGrid中显示的一行,其中包括:
Header   DataGrid 控件的标题部分
Item   DataGrid 控件中的项
AlternatingItem  DataGrid 控件中的交替项
SelectedItem    DataGrid 控件中的选定项(由SelectedIndex设置,通过SelectedItem属性或者Items[SelectedIndex]来读取)
EditItem    DataGrid 控件中处于编辑状态的项(由EditItemIndex设置,通过Items[EditItemIndex]来读取)
Separator    DataGrid 控件中项之间的分隔符
Footer    DataGrid 控件的脚注部分
Pager     DataGrid 控件的页选择节
注意,DataGrid的Items属性中不会包含Header、Footer、Pager这三类DataGridItem的。
5.1.1、DataGridItem的属性
ItemIndex -- 得到行在Items中的索引
ItemType -- 返回行的类型,也就是上面列出的Header、Item、...、Pager
Cells -- 返回行包含的所有TableCell(不管是显示声明的,还是自动生成的,不管是可以看见的,还是隐藏掉的),通过TableCell,可以读取Cell中显示的文本、包含的控件
严重注意:只有BoundColumn列和自动生成列,才可以通过TableCell.Text属性读取显示的文本。HyperLinkColumn、ButtonColumn、EditCommandColumn都需要将目标控件转换成相应的控件。
比如:
假设DataGrid的第一列声明如下
<asp:HyperLinkColumn DataTextField="au_id" HeaderText="au_id" DataNavigateUrlField="au_id" DataNavigateUrlFormatString="Edit.aspx?id={0}"></asp:HyperLinkColumn>
读取的时候可以用:
//Items[0]表示第一行,Cells[0]表示第一列,Controls[0]表示Cell中的第一个控件(也只有这个控件可以用)
HyperLink link = (HyperLink)DataGrid1.Items[0].Cells[0].Controls[0]);
Response.Write(link.Text);
至于模板列(TemplateColumn),当然也可以通过DataGrid1.Items[i].Cells[j].Controls[n]来获取,然后转换成原来的控件类型再操作,但是还有个更好的办法,就是用FindControl来查找控件。
FindControl是System.Web.UI.Control的方法,可以根据子控件ID来查找子控件
比如:
假设DataGrid的某一列声明如下
<asp:TemplateColumn>
   <ItemTemplate>
      <asp:TextBox Runat="server" ID="txtID" Text='<%# DataBinder.Eval(Container.DataItem,"au_id") %>'>
      </asp:TextBox>
   </ItemTemplate>
</asp:TemplateColumn>
读取方法:
TextBox txt = (TextBox)DataGrid1.Items[1].FindControl("txtID");
Response.Write(txt.Text);
注意:DataList中是没有Cell的


三、事件
1、ItemCommand、CancelCommand、DeleteCommand、EditCommand、UpdateCommand
也就是DataGrid中,点击Button、LinkButton后执行的事件,执行的事件取决于按钮的CommandName。其实最主要的一个是ItemCommand,而后面四个都只是ItemCommand的一小部分,
比如一个按钮的CommandName为"Cancel",当返回后,首先执行的是ItemCommand事件,然后才是CancelCommand事件。

2、PageIndexChanged
如果你的DataGrid是分页的,那当你在DataGrid上点击Pager上的1、2、3或者<、>时,就会激发这个事件。
在这个事件里面,你可以用e.NewPageIndex来读取要改变的页,然后赋值给DataGrid的CurrentPageIndex属性,最后不要忘了,还要设置DataSource,还要执行DataBind。
注意:DataList中没有这个事件,如果需要在DataList中分页,可以一段一段的读取数据,然后把当前段的数据绑定到DataList上。

3、ItemDataBound,ItemCreated
首先要说的是这两个事件的发生时间。
ItemDataBound嘛,只要执行了DataBind方法,就会马上激发这个事件。
ItemCreated呢,如果页面是第一次访问(Page.IsPostBack = false),那在第一次执行DataBind的时候,会先激发ItemCreated事件,也就是说,执行了DataBind后,首先会用ItemCreated来建立Header行,然后用ItemDataBound来绑定Header行,再用ItemCreated来建立第一行,再调用ItemDataBound来绑定第一行,也就是说ItemCreated和ItemDataBound是交替执行的。
页面返回时,也会执行ItemCreated事件,在Page_Load之前,但是这时候就不会再执行ItemDataBound事件了。
所以,如果你想在DataGrid里动态添加什么控件,就需要在ItemCreated事件中,而不是在ItemDataBound事件中。


四、代码片断
1、DataGrid显示双层表头
假设你的DataGrid有三列,现在想将前两列作为"大类1",第三列作为"大类2",现在,你可以在ItemDataBound事件中加入下面的代码:
if (e.Item.ItemType == ListItemType.Header)
{
 e.Item.Cells[0].ColumnSpan = 2;
 e.Item.Cells[0].Text = "大类1</td><td>大类2</td></tr><tr><td>" + e.Item.Cells[0].Text;
}
用这个方法可以为任意添加新行。

2、设置绑定列或者自动生成列的编辑框宽度
请在你的ItemDataBound事件中加入一下代码:
if (e.Item.ItemType == ListItemType.EditItem)
{
 for (int i = 0; i < e.Item.Cells.Count; i++)
 {
  TextBox txt = (TextBox)e.Item.Cells[i].Controls[0];
  txt.Width = Unit.Pixel(50);
 }
}

3、处理在DataGrid中的DropDownList的事件
DropDownList没有CommandName属性,所以不能用ItemCommand事件,不过你可以这样试试:
在DataGrid的模板列中加入的DropDownList控件
<asp:DropDownList runat="server" id="ddl" AutoPostBack="True" OnSelectedIndexChanged="ddl_SelectedIndexChanged" />
然后你在.aspx.cs中加入一个函数
protected void ddl_SelectedIndexChanged(object sender, System.EventArgs e) //一定要声明成protected或者public,不能是private的。
{
  //在这里就可以加入其他代码
}

3.1、在上面的事件中怎样得到本行其他Cell的值呢?
我们知道,DataGrid完全是一个Table结构的控件,DataGrid包含DataGridItem,每个DataGridItem又包含TableCell,那么,我们就可以在TableCell的某个控件中,利用控件的Parent来得到TableCell,再利用TableCell的Parent,就可以得到DataGridItem了。
protected void ddl_SelectedIndexChanged(object sender, System.EventArgs e) //一定要声明成protected或者public,不能是private的。
{
  DropDownList ddl = (DropDownList)sender;
  TableCell cell = (TableCell)ddl.Parent;
  DataGridItem item = (DataGridItem)cell.Parent;
  Response.Write(item.Cells[0].Text);
}

4、怎样得到Header、Footer、Pager里的控件
方法一:在ItemCreated或者ItemDataBound中,具体代码就不在多写了
方法二:遍历DataGrid的所有Item(注意,不是遍历DataGrid1.Items下的Item)
foreach (DataGridItem item in DataGrid1.Controls[0].Controls)
{
  if (item.ItemType == ListItemType.Header)
  {
    //用item.FindControl查找相应的控件
  }
}
大家可能会注意到,这里有个DataGrid1.Controls[0].Controls,这表示,DataGrid1下,有一个子控件,这个子控件是DataGridTable类型,他下面才是DataGridItem集合
在DataList中,下面的子控件直接就是DataListItem了,而没有Table:
foreach (DataListItem item in DataList1.Controls)
{
  //....
}

 


//from msdn by lyh
Selecting Rows by Clicking Anywhere
The default model for selecting rows in the grid is for you to add a Select button (actually, a LinkButton control) whose CommandName property is set to "Select." When the button is clicked, the DataGrid control receives the Select command and automatically displays the row in selected mode.

Not everyone likes having an explicit Select button, and a common question is how to implement the feature where users can click anywhere in a grid row to select it. The solution is to perform a kind of sleight-of-hand in the grid. You add the Select LinkButton control as normal. Users can still use it, or you can hide it. In either event, you then inject some client script into the page that effectively duplicates the functionality of the Select button for the row as a whole.

The example below shows how. In the grid's ItemDataBound handler, first make sure that you are not in the header, footer, or pager. Then get a reference to the Select button, which in this instance is assumed to be the first control in the first cell. You then call a little-known method called GetPostBackClientHyperlink. This method returns the name of the postback call for the designated control. In other words, if you pass in a reference to a LinkButton control, it returns the name of the client function call that will perform the postback.

Finally, you assign the client-side method to the item itself. When the grid renders, it renders as an HTML table. By assigning the method to the item, it is the equivalent of adding client-side code to each row (<TR> element) in the table. The grid's Item object does not directly support a way to assign client code to it, but you can do that by using its Attributes collection, which passes anything you assign to it through to the browser.

Note   One small disadvantage of this technique is that it adds somewhat to the stream rendered to the browser, and it adds information for each row to view state.
' Visual Basic
Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, _
      ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) _
      Handles DataGrid1.ItemDataBound
   Dim itemType As ListItemType = e.Item.ItemType
   If ((itemType = ListItemType.Pager) Or _
      (itemType = ListItemType.Header) Or _
      (itemType = ListItemType.Footer)) Then
      Return
   Else
      Dim button As LinkButton = _
         CType(e.Item.Cells(0).Controls(0), LinkButton)
      e.Item.Attributes("onclick") = _
         Page.GetPostBackClientHyperlink(button, "")
   End If
End Sub

// C#
private void DataGrid1_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
   ListItemType itemType = e.Item.ItemType;
   if ((itemType == ListItemType.Pager) ||
       (itemType == ListItemType.Header) ||
       (itemType == ListItemType.Footer))
   {
      return;
   }
   LinkButton button = (LinkButton)e.Item.Cells[0].Controls[0];
   e.Item.Attributes["onclick"] =
      Page.GetPostBackClientHyperlink(button, "");

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在语文教育中,C可以代表“写作”和“创作”。写作是通过文字表达思想和情感的一种方式,是提高语文素养的重要途径之一。写作可以帮助我们整理思绪,提高表达能力和逻辑思维能力。通过写作,我们可以将自己的想法和感受转化为具体而准确的语言,使读者能够更好地理解我们的观点。 写作可以分为实用写作和文学写作两种类型。实用写作是指为满足实际需求而进行的写作,比如写作公告、作文等。实用写作要求清晰明了、准确简练。文学写作则追求艺术性和情感表达,包括诗歌、小说、散文等。文学写作对表达能力和想象力要求较高,可以带给读者更多的审美享受。 创作是在写作基础上更进一步,是创造性的写作。创作可以是在现实基础上进行再创造,创造自己的世界观和价值观。创作可以是对现实的反思和思考,也可以是对未来的设想和展望。通过创作,我们可以培养自己的创造力、独立思考能力和想象力,提高自己的审美能力和艺术表达能力。 总之,在语文教育中,“写作”和“创作”是重要的学习内容和能力培养方向。通过写作和创作,我们可以提高自己的语文素养,增强自己的表达能力和思维能力,培养自己的创造力和审美能力,提高自己的综合素质。只有通过实践和不断的努力,我们才能在写作和创作中取得更好的成绩和进步。 ### 回答2: c是一种编程语言,最初是由丹尼斯·里奇在20世纪70年代末开发的。c语言是一种通用的高级编程语言,其设计的目标是提供一种仅仅依赖于简单的计算机指令的编程环境。 c语言具备很强的灵活性和可移植性,使其成为一门非常流行的编程语言。由于c语言的特点,它被广泛用于各种应用程序的开发,如操作系统、嵌入式系统、图形用户界面、编译器等。同时,c语言也是许多其他编程语言的基础。 c语言的语法简洁且易于理解,所以它很适合于初学者学习。它提供了一系列的基本语句和控制结构,允许程序员通过编写函数和模块化程序来构建复杂的应用。 此外,c语言还支持指针操作,这是一种强大而灵活的机制,可以直接访问和修改计算机内存的内容。这使得c语言可以进行高效的内存管理和低级别的系统编程。 总的来说,c语言是一门强大、灵活且流行的编程语言。它在计算机科学和软件工程领域具有广泛的应用和影响力。无论是初学者还是专业程序员,学习c语言都是值得的。 ### 回答3: C是一种计算机编程语言,它由美国贝尔实验室的丹尼斯·里奇(Dennis Ritchie)在1972年开发出来。C语言是一种通用的、面向过程的编程语言,被广泛应用于系统软件、驱动程序和嵌入式系统的开发中。 C语言的设计目标是提供一种能够通过简洁的语法和丰富的表达力来编写高效、可移植和可维护的代码的编程语言。C语言的语法简洁而精确,操作符和控制结构的数量较少,易于学习和理解。它具有高度的灵活性和可扩展性,可以用来实现各种复杂的算法和数据结构。 C语言具有较高的性能和效率,在编译后的程序执行速度快,占用的系统资源少。它支持底层的位操作和指针操作,可以直接访问内存,能够对硬件资源进行更加精细的控制,因此在开发操作系统、驱动程序和嵌入式系统时被广泛使用。 C语言有着丰富的函数库,开发者可以通过调用这些函数来完成各种任务,例如文件操作、字符串处理、数学计算等。此外,C语言也支持通过指针进行内存管理,可以动态分配和释放内存,方便进行数据结构的动态存储和处理。 总之,C语言是一种强大而灵活的编程语言,具有高效性、可移植性和可维护性的特点,被广泛应用于各种系统软件和嵌入式系统的开发中。它为开发者提供了丰富的工具和功能,使得他们能够用简单而优雅的代码实现复杂的任务。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值