Insert Row between two rows
-
27-09-2019 - |
Question
We are using ASP.NET 1.1 for a website development, using DataGrid control for showing data.
Can some body suggest how can i insert rows in between two rows in datagrid control.
Thanks,
-Narendra
Solution
You'll have to insert that row in your data source - perhaps a DataTable.
Then you'll have to ensure that the grid is sorted as per your requirement. You're wanting the new row in a specific spot, so perhaps implement a SortOrder column on your DataTable, and explicitly update the values in that column for all the rows below the new row, as per your requirements, before binding.
OTHER TIPS
You can insert the new row to the datasource (for example a DataTable). DataRowCollection has a Function InsertAt that lets you insert rows at the position you want.
I will provide a simple example (in VB.Net with a GridView, DataGrid works the same):
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>
Codebehind:
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