使用DataGrid容易范的几个错误。

  这几天,把以前一个项目改了一下,在对程序的调试过程中,出现了一些使用DataGrid的错误。对DataGrid的理解也更深了一些。
1、在使用模板列时,发现在非编辑状态下,用e.Item.Cell(0).text总取不到值,后来跟踪调试了一下,发现e.Item.Cell(0).Text的值为空。但是其Controls里有Label控件。我恍然大悟。一想也对。既然在编辑状态下取的是TextBox的值,在非编辑状态下应该是Label啊。呵呵,从这里也对模板列的理解深了一点。
.对模板列,可以这样用:

If DataGrid1.EditItemIndex = e.Item.ItemIndex Then
            Device 
= CType(e.Item.Cells(1).FindControl("txtDevice"), TextBox).Text.Trim()
 
Else
            Device 
= CType(e.Item.Cells(1).FindControl("lblDevice"), Label).Text.Trim()
End If
2、在删除的时候,如果删除的是页面的第一项,删除后,CurrentPageIndex要向前一页。这点容易忽略。
If (DataGrid1.Items.Count Mod DataGrid1.PageSize = 1And DataGrid1.CurrentPageIndex <> 0 Then
                DataGrid1.CurrentPageIndex 
-= 1
End If

3、添加一个新项后转到最后一页。这点没什么必要。但是做出来显得更人性化一点。
If DataGrid1.Items.Count Mod ataGrid1.PageSize = 0 Then
                        DataGrid1.CurrentPageIndex 
= ataGrid1.PageCount
Else
                        DataGrid1.CurrentPageIndex 
= DataGrid1.PageCount - 1
End If

可能这些小技巧对于高手们来说已经司空见惯了。但我研究解决这些问题,最后学到新知识的过程是非常令人愉快的。所以在这里记下来。
posted @ 2005-04-24 00:14  haitoo  阅读(525)  评论(0编辑  收藏  举报