在两行之间插入行

时间:2010-11-23 18:07:55

标签: asp.net .net-1.1 asp.net-1.1

我们使用ASP.NET 1.1进行网站开发,使用DataGrid控件显示数据。

有些正文可以建议我如何在datagrid控件中的两行之间插入行。

谢谢,

-Narendra

2 个答案:

答案 0 :(得分:0)

您必须在数据源中插入该行 - 可能是DataTable。

然后,您必须确保根据您的要求对网格进行排序。您希望在特定位置使用新行,因此可能在DataTable上实现SortOrder列,并根据您的要求显式更新该列中新行下方的所有行的值,在绑定之前。

答案 1 :(得分:0)

您可以将新行插入数据源(例如DataTable)。 DataRowCollection具有函数InsertAt,允许您在所需位置插入行。

我将提供一个简单的例子(在VB.Net中使用GridView,DataGrid的工作方式相同):

ASPX:

 <asp:GridView ID="MyGrid" runat="server" AutoGenerateColumns="true">
        </asp:GridView>
        <asp:Button ID="BtnInsert" runat="server" Text="insert Obama at Position" /><asp:TextBox ID="TxtPosition" Text="0" runat="server"></asp:TextBox>

代码隐藏:

   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindData(getDataSource())
        End If
    End Sub

    Private Function getDataSource() As DataTable
        Dim tbl As New DataTable
        Dim col As New DataColumn("ID", GetType(Int32))
        tbl.Columns.Add(col)
        col = New DataColumn("FirstName", GetType(String))
        tbl.Columns.Add(col)
        col = New DataColumn("LastName", GetType(String))
        tbl.Columns.Add(col)
        Dim row As DataRow = tbl.NewRow
        row("ID") = 1
        row("FirstName") = "Benjamin"
        row("LastName") = "Franklin"
        tbl.Rows.Add(row)
        row = tbl.NewRow
        row("ID") = 2
        row("FirstName") = "Arnold"
        row("LastName") = "Schwarzenegger"
        tbl.Rows.Add(row)
        row = tbl.NewRow
        row("ID") = 3
        row("FirstName") = "Albert"
        row("LastName") = "Einstein"
        tbl.Rows.Add(row)
        row = tbl.NewRow
        row("ID") = 4
        row("FirstName") = "Bill"
        row("LastName") = "Gates"
        tbl.Rows.Add(row)
        Return tbl
    End Function

    Private Sub BindData(ByVal source As DataTable)
        Me.MyGrid.DataSource = source
        Me.MyGrid.DataBind()
    End Sub

    Private Sub BtnInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnInsert.Click
        Dim pos As Int32 = 0
        Int32.TryParse(TxtPosition.Text, pos)
        Dim source As DataTable = Me.getDataSource()
        If pos < 0 OrElse pos > source.Rows.Count Then pos = 0
        Dim row As DataRow = source.NewRow
        row("ID") = 5
        row("FirstName") = "Barack"
        row("LastName") = "Obama"
        source.Rows.InsertAt(row, pos)'this is the only important'
        BindData(source)
    End Sub