2010-11-23 89 views
1

我們使用ASP.NET 1.1進行網站開發,使用DataGrid控件顯示數據。在兩行之間插入行

可以有人建議如何插入行中的兩行之間的數據網格控件。

感謝,

-Narendra

+0

或許表現出一定的代碼你如何約束? – 2010-11-23 18:12:56

回答

0

你必須插入該行的數據源 - 也許是一個DataTable。

然後你必須確保網格根據你的要求排序。您需要在特定位置放置新行,因此可能需要在DataTable上實現SortOrder列,然後根據需要在綁定前明確更新該列中的值新行以下的所有行。

+0

感謝坎貝爾的回覆。我試着添加一行到數據表中,並用最新的數據表格重新綁定數據網格,但沒有運氣。新添加的行將添加到最後一行中。 – 2010-11-23 18:21:19

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