473,468 Members | 1,347 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to Insert a row at any position in grid view?

96 New Member
I want to insert the record at any position in a grid view means
means if i add Insert buuton at every row of grid view.
& when i click on insert button of an perticular row a new row is created just next to this row on which i click.
But it does not made any effect on its id.
i make my id auto incremented so i just want to insert record at any position but id remain as its in a usual manner

supoose i add 7 record i have 7 record id is 7 & i click on a insert button of id 7 record then now row is display to insert the reord just next to record 3 & the inserted record id should show 8 id

like this
1
2
3---------> click on that row
8------>new inserted record
4
5
6
7
May 24 '10 #1
3 8817
Frinavale
9,735 Recognized Expert Moderator Expert
I'm sorry I took so long to reply but I've been pretty busy over the last few days.
What you need to do is...in the RowCommand event:
  • Retrieve the Row that Insert link button that was clicked belongs to. The way that I did this was to bind the CommandArgument for the Insert link button to the Container's (the GidView's) DataItemIndex. This way I was able to retrieve the row based on the index supplied as the CommandArgument in the RowCommand event.
  • Retrieve the ID of the item selected.
  • Find the Index of the selected item in your data source.
  • Insert a new item into your data source at the next index.
  • Set the GridView's RowEditIndex to row under the row that was clicked on.

I tried this out using the testing code based on the code that you posted previously in this thread: How to update a database without using SqlDataSource.

Here is the GridView markup. Please note that I changed the ID of "Label6" to "DummyID" to better reflect the value that it is displaying. Also, please note that I have added code that binds the CommandArgument for each LinkButton to the RowIndex of the item in the GridView...and I've also added Paging.
Expand|Select|Wrap|Line Numbers
  1. <asp:GridView ID="gv_DisplayClient" runat="server" DataKeyNames="DummyID" ForeColor="#333333"
  2.     GridLines="Horizontal" CellPadding="4" AutoGenerateColumns="false" OnRowEditing="GvEditing"
  3.     OnRowCancelingEdit="gv_EditCancel" EnableViewState="true" OnRowUpdating="gv_Updating"
  4.     OnRowDeleting="gv_Deleting" OnRowCommand="gv_DisplayClient_RowCommand" ShowFooter="true"
  5.     AllowPaging="true" OnPageIndexChanging="gv_DisplayClient_OnPageIndexChanging" PageSize="5">
  6.     <PagerSettings Mode="NumericFirstLast" Position="Top" />
  7.     <Columns>
  8.         <asp:TemplateField HeaderText="ClientId">
  9.             <ItemTemplate>
  10.                 <asp:Label ID="DummyID" runat="server" Text='<%#Bind("DummyID")%>'></asp:Label>
  11.             </ItemTemplate>
  12.             <FooterTemplate>
  13.                 <asp:Label ID="LblInsertPrompt" runat="server" Text="New Dummy:"></asp:Label>
  14.             </FooterTemplate>
  15.         </asp:TemplateField>
  16.         <asp:TemplateField HeaderText="ClientName">
  17.             <ItemTemplate>
  18.                 <asp:Label ID="lblClientName" runat="server" Text='<%#Eval("ClientName")%>'></asp:Label>
  19.             </ItemTemplate>
  20.             <EditItemTemplate>
  21.                 <asp:TextBox ID="gvClientName" runat="server" Text='<%#Bind("ClientName")%>'></asp:TextBox>
  22.             </EditItemTemplate>
  23.             <FooterTemplate>
  24.                 <asp:TextBox ID="gvClientName" runat="server"></asp:TextBox>
  25.             </FooterTemplate>
  26.         </asp:TemplateField>
  27.         <asp:TemplateField HeaderText="Address">
  28.             <ItemTemplate>
  29.                 <asp:Label ID="lblAddress" runat="server" Text='<%#Eval("Address")%>'></asp:Label>
  30.             </ItemTemplate>
  31.             <EditItemTemplate>
  32.                 <asp:TextBox ID="gvAddress" runat="server" Text='<%#Bind("Address")%>'></asp:TextBox>
  33.             </EditItemTemplate>
  34.             <FooterTemplate>
  35.                 <asp:TextBox ID="gvAddress" runat="server"></asp:TextBox>
  36.             </FooterTemplate>
  37.         </asp:TemplateField>
  38.         <asp:TemplateField HeaderText="MobileNo">
  39.             <ItemTemplate>
  40.                 <asp:Label ID="lblMobileNo" runat="server" Text='<%#Eval("MobileNo")%>'></asp:Label>
  41.             </ItemTemplate>
  42.             <EditItemTemplate>
  43.                 <asp:TextBox ID="gvMobileNo" runat="server" Text='<%#Bind("MobileNo")%>'></asp:TextBox>
  44.             </EditItemTemplate>
  45.             <FooterTemplate>
  46.                 <asp:TextBox ID="gvMobileNo" runat="server"></asp:TextBox>
  47.             </FooterTemplate>
  48.         </asp:TemplateField>
  49.         <asp:TemplateField HeaderText="Image">
  50.             <ItemTemplate>
  51.                 <asp:Label ID="lblImage" runat="server" Text='<%#Eval("Image")%>'></asp:Label>
  52.             </ItemTemplate>
  53.             <EditItemTemplate>
  54.                 <asp:TextBox ID="gvImage" runat="server" Text='<%#Bind("Image")%>'></asp:TextBox>
  55.             </EditItemTemplate>
  56.             <FooterTemplate>
  57.                 <asp:TextBox ID="gvImage" runat="server" Text='<%#Bind("Image")%>'></asp:TextBox>
  58.             </FooterTemplate>
  59.         </asp:TemplateField>
  60.         <asp:TemplateField HeaderText="Operations">
  61.             <ItemTemplate>
  62.                 <asp:LinkButton ID="editRow" runat="server" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>' Text="Edit" ForeColor="#284775"></asp:LinkButton>
  63.                 <asp:LinkButton ID="deleteRow" runat="server" CommandName="Delete" CommandArgument='<%# Container.DataItemIndex %>' Text="Delete" ForeColor="#284775"></asp:LinkButton>
  64.                 <asp:LinkButton ID="insertRow" runat="server" CommandName="Insert" CommandArgument='<%# Container.DataItemIndex %>' Text="Insert" ForeColor="#284775"></asp:LinkButton>
  65.             </ItemTemplate>
  66.             <EditItemTemplate>
  67.                 <asp:LinkButton ID="btnupdate" runat="server" CommandName="Update"  CommandArgument='<%# Container.DataItemIndex %>' Text="Update"
  68.                     ForeColor="#284775"></asp:LinkButton>
  69.                 <asp:LinkButton ID="btncancel" runat="server" CommandName="Cancel" CommandArgument='<%# Container.DataItemIndex %>' Text="Cancel" 
  70.                     ForeColor="#284775"></asp:LinkButton>
  71.             </EditItemTemplate>
  72.             <FooterTemplate>
  73.                 <asp:LinkButton ID="btnAdd" runat="server" CommandName="InsertNew" Text="Insert New"
  74.                     ForeColor="White"></asp:LinkButton>
  75.             </FooterTemplate>
  76.         </asp:TemplateField>
  77.     </Columns>
  78.     <RowStyle BackColor="#F7F6F3" ForeColor="#000000" />
  79.     <HeaderStyle BackColor="#284775" ForeColor="AliceBlue" Font-Bold="true" />
  80.     <FooterStyle BackColor="#284775" ForeColor="AliceBlue" />
  81.     <PagerStyle BackColor="#A2B5CD" ForeColor="White" HorizontalAlign="Center" />
  82.     <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
  83.     <EditRowStyle BackColor="#999999" />
  84.     <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
  85. </asp:GridView>

Here is the DummyBLL class that I'm using as the DataSource for the GridView. It's pretty much the same except that it has an Insert method that allows me to insert a new DummyBLL. I also changed the default list of DummyBLLs that is used for the source so that the DummyBLL's ID's start at 1 instead of 0 (like in the previous version).

The reason I started the IDs at 1 was to be able to tell if the user was editing a "new" DummyBLL by checking if the ID is 0. If the DummyBLL's ID is 0 then, when the user is canceling the edit I remove it from the data source...likewise if the user is updating I will assign the DummyBLL the real ID at that point.

Here is the code for the DummyBLL class.
Notice how I added the Insert method. I also modified the Update method. In the Update method I check to see if it's a "new" DummyBLL (id = 0) and if so I assign it a new ID. I also changed the Update method to not just add a new DummyBLL onto the end of my list...it retrieves the index of the Dummy being edited and updates the Dummy at that index.
Expand|Select|Wrap|Line Numbers
  1. protected void gv_Deleting(object sender, GridViewDeleteEventArgs e)
  2. {
  3.     Label lbl = (Label)gv_DisplayClient.Rows[e.RowIndex].FindControl("DummyID");
  4.  
  5.     Int32 dummyID = Convert.ToInt32(lbl.Text);
  6.     DummyBLL.delete(dummyID);
  7.     display();
  8. }
  9.  
  10. private void display()
  11. {
  12.     gv_DisplayClient.DataSource = DummyBLL.display();
  13.     gv_DisplayClient.DataBind();
  14. }
  15.  
  16. private class DummyBLL
  17. {
  18.     private static List<DummyBLL> _source;
  19.     private Int32 _id;
  20.     private String _name;
  21.     private String _address;
  22.     private String _mobileNo;
  23.     private String _image;
  24.  
  25.     public Int32 DummyID
  26.     {
  27.         get { return _id; }
  28.         set { _id = value; }
  29.     }
  30.     public String ClientName
  31.     {
  32.         get { return _name; }
  33.         set { _name = value; }
  34.     }
  35.     public String Address
  36.     {
  37.         get { return _address; }
  38.         set { _address = value; }
  39.     }
  40.     public String MobileNo
  41.     {
  42.         get { return _mobileNo; }
  43.         set { _mobileNo = value; }
  44.     }
  45.     public String Image
  46.     {
  47.         get { return _image; }
  48.         set { _image = value; }
  49.     }
  50.  
  51.     public static List<DummyBLL> display()
  52.     {
  53.         List<DummyBLL> source = new List<DummyBLL>();
  54.         if (HttpContext.Current.Session["_source"] != null)
  55.         {
  56.             _source = (List<DummyBLL>)HttpContext.Current.Session["_source"];
  57.             source = _source;
  58.         }
  59.         else
  60.         {
  61.             String[] names = { "Bob", "Sally", "Frank", "Steve", "Beth", "Pat", "Joan", "Howard" };
  62.  
  63.             int i = 0;
  64.             foreach (string name in names)
  65.             {
  66.                 source.Add(new DummyBLL(i + 1, name, name + "'s address", "1-999-333-222" + i.ToString(), name + "'s picture"));
  67.                 i++;
  68.             }
  69.         }
  70.         _source = source;
  71.         HttpContext.Current.Session["_source"] = _source;
  72.         return source;
  73.     }
  74.     public DummyBLL()
  75.     {
  76.         _id = 0;
  77.         _name = "";
  78.         _address = "";
  79.         _mobileNo = "";
  80.         _image = "";
  81.     }
  82.     public DummyBLL(Int32 id, String name, String address, String mobileNo, String imgName)
  83.     {
  84.         _id = id;
  85.         _name = name;
  86.         _address = address;
  87.         _mobileNo = mobileNo;
  88.         _image = imgName;
  89.     }
  90.     public static void add(DummyBLL newDummyBLL)
  91.     {
  92.         _source = display();
  93.  
  94.         if (newDummyBLL.DummyID == 0)
  95.         {
  96.             newDummyBLL.DummyID = _source.Count + 1;
  97.         }
  98.  
  99.         _source.Add(newDummyBLL);
  100.         HttpContext.Current.Session["_source"] = _source;
  101.     }
  102.     public static void delete(Int32 id)
  103.     {
  104.         _source = display();
  105.         DummyBLL toDelete = Array.Find<DummyBLL>(_source.ToArray(), (x) => x.DummyID == id);
  106.         if (toDelete != null)
  107.         {
  108.             _source.Remove(toDelete);
  109.         }
  110.         HttpContext.Current.Session["_source"] = _source;
  111.     }
  112.     public static void update(DummyBLL updatedDummy)
  113.     {
  114.         Int32 id = updatedDummy.DummyID;
  115.         _source = display();
  116.         DummyBLL toDelete = Array.Find<DummyBLL>(_source.ToArray(), (x) => x.DummyID == id);
  117.  
  118.         if (toDelete != null)
  119.         {
  120.             Int32 indexOfDummyDeleted = Array.FindIndex(_source.ToArray(), (x) => x.DummyID == toDelete.DummyID);
  121.             _source.Remove(toDelete);
  122.             if (id == 0)
  123.             {
  124.                 updatedDummy.DummyID = _source.Count + 1;
  125.             }
  126.             _source.Insert(indexOfDummyDeleted, updatedDummy);
  127.         }
  128.         else
  129.         {
  130.             if (id == 0)
  131.             {
  132.                 updatedDummy.DummyID = _source.Count + 1;
  133.             }
  134.             _source.Add(updatedDummy);
  135.         }
  136.         HttpContext.Current.Session["_source"] = _source;
  137.     }
  138.     public static void Insert(DummyBLL newDummy, Int32 index)
  139.     {
  140.         _source = display();
  141.         _source.Insert(index, newDummy);
  142.         HttpContext.Current.Session["_source"] = _source;
  143.     }
  144.  
  145. }

Last but not least this is the code for the RowCommand, Paging, and the other GridView events...as well as the Page Load event. The RowCommand does everything that I outlined in the steps that you need to do in order to insert a new row.
Expand|Select|Wrap|Line Numbers
  1. protected void Page_Load(object sender, EventArgs e)
  2. {    if (IsPostBack == false)
  3.      {  display();  }
  4. }
  5.  
  6. protected void gv_DisplayClient_RowCommand(Object sender, GridViewCommandEventArgs e)
  7. {
  8.     switch (e.CommandName)
  9.     {
  10.         case "Insert":
  11.  
  12.             //The Command argument is the index of the row in the GridView clicked on.
  13.             //If the GridView supports paging, this is not necessarily the index of the row being shown.
  14.             //To get the index of the row you need to take into consideration the page size etc.            
  15.             int insertRowIndex;
  16.             if (int.TryParse(e.CommandArgument.ToString(), out insertRowIndex))
  17.             {
  18.                 insertRowIndex = insertRowIndex - (gv_DisplayClient.PageIndex * gv_DisplayClient.PageSize);
  19.                 GridViewRow row = gv_DisplayClient.Rows[insertRowIndex];
  20.                 int id = Convert.ToInt32(((Label)row.FindControl("DummyID")).Text);
  21.                 DummyBLL newDummy = new DummyBLL();
  22.                 Int32 insertIndex = Array.FindIndex(DummyBLL.display().ToArray(), (d) => d.DummyID == id);
  23.                 DummyBLL.Insert(newDummy, insertIndex + 1);
  24.  
  25.                 //Checking to see if the index of the row we are editing is on the same page
  26.                 //If it's not then we need to change to the page where the item is inserted
  27.                 if (insertRowIndex + 1 > gv_DisplayClient.PageSize-1)
  28.                 {
  29.                     gv_DisplayClient.PageIndex = gv_DisplayClient.PageIndex + 1;
  30.                     gv_DisplayClient.EditIndex = 0;
  31.                 }
  32.                 else
  33.                 {
  34.                     gv_DisplayClient.EditIndex = insertRowIndex + 1;
  35.                 }
  36.                 display();
  37.             }
  38.             break;
  39.         case "InsertNew":
  40.             GridViewRow rowNewToInsert = gv_DisplayClient.FooterRow;
  41.             if (rowNewToInsert != null)
  42.             {
  43.                 gv_DisplayClient.EditIndex = -1;
  44.  
  45.                 TextBox tx1 = (TextBox)rowNewToInsert.FindControl("gvClientName");
  46.                 TextBox tx2 = (TextBox)rowNewToInsert.FindControl("gvAddress");
  47.                 TextBox tx3 = (TextBox)rowNewToInsert.FindControl("gvMobileNo");
  48.                 TextBox tx4 = (TextBox)rowNewToInsert.FindControl("gvImage");
  49.                 DummyBLL dummy = new DummyBLL();
  50.                 dummy.ClientName = tx1.Text;
  51.                 dummy.Address = tx2.Text;
  52.                 dummy.MobileNo = tx3.Text;
  53.                 dummy.Image = tx4.Text;
  54.                 DummyBLL.add(dummy);
  55.                 display();
  56.             }
  57.             break;
  58.         case "Cancel":
  59.             int cancelRowIndex;
  60.             if (int.TryParse(e.CommandArgument.ToString(), out cancelRowIndex))
  61.             {
  62.                 cancelRowIndex = cancelRowIndex - (gv_DisplayClient.PageIndex * gv_DisplayClient.PageSize);
  63.                 GridViewRow row = gv_DisplayClient.Rows[cancelRowIndex];
  64.                 int id = Convert.ToInt32(((Label)row.FindControl("DummyID")).Text);
  65.                 if (id == 0)
  66.                 {
  67.                     DummyBLL.delete(id);
  68.                 }
  69.             }
  70.  
  71.             break;
  72.     }
  73. }
  74.  
  75. protected void gv_DisplayClient_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
  76. {
  77.     if (e.NewPageIndex >= 0 && e.NewPageIndex < gv_DisplayClient.PageCount)
  78.     {
  79.         gv_DisplayClient.PageIndex = e.NewPageIndex;
  80.         display();
  81.     }
  82. }
  83. protected void GvEditing(object sender, GridViewEditEventArgs e)
  84. {
  85.     gv_DisplayClient.EditIndex = e.NewEditIndex;
  86.     display();
  87. }
  88. protected void gv_EditCancel(object sender, GridViewCancelEditEventArgs e)
  89. {
  90.     gv_DisplayClient.EditIndex = -1;
  91.     display();
  92. }
  93. protected void gv_Updating(object sender, GridViewUpdateEventArgs e)
  94. {
  95.  
  96.     Label lb = (Label)gv_DisplayClient.Rows[e.RowIndex].FindControl("DummyID");
  97.     int ClientId = Convert.ToInt32(lb.Text);
  98.     TextBox tx1 = (TextBox)gv_DisplayClient.Rows[e.RowIndex].FindControl("gvClientName");
  99.     TextBox tx2 = (TextBox)gv_DisplayClient.Rows[e.RowIndex].FindControl("gvAddress");
  100.     TextBox tx3 = (TextBox)gv_DisplayClient.Rows[e.RowIndex].FindControl("gvMobileNo");
  101.     TextBox tx4 = (TextBox)gv_DisplayClient.Rows[e.RowIndex].FindControl("gvImage");
  102.     DummyBLL dummy = new DummyBLL();
  103.     dummy.ClientName = tx1.Text;
  104.     dummy.Address = tx2.Text;
  105.     dummy.MobileNo = tx3.Text;
  106.     dummy.Image = tx4.Text;
  107.     dummy.DummyID = ClientId;
  108.     DummyBLL.update(dummy);
  109.     gv_DisplayClient.EditIndex = -1;
  110.     display();
  111.  
  112. }
  113. protected void gv_Deleting(object sender, GridViewDeleteEventArgs e)
  114. {
  115.     Label lbl = (Label)gv_DisplayClient.Rows[e.RowIndex].FindControl("DummyID");
  116.  
  117.     Int32 dummyID = Convert.ToInt32(lbl.Text);
  118.     DummyBLL.delete(dummyID);
  119.     display();
  120. }
  121.  
  122. private void display()
  123. {
  124.     gv_DisplayClient.DataSource = DummyBLL.display();
  125.     gv_DisplayClient.DataBind();
  126. }
  127.  
-Frinny
May 26 '10 #2
AnagJohari
96 New Member
You are great man, i am still not checking but the logic you use i know it will work fine.
Thaks a lot my dear frnd
frinny can you add me as ur frnd ,
.
May 26 '10 #3
Frinavale
9,735 Recognized Expert Moderator Expert
Sure :)
I just wish there was a way around the language barrier between us because, judging by your logic/code and your desire to learn, you seem like the sort of person that I would like to chat with from time to time :)
May 26 '10 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: ¿ Mahesh Kumar | last post by:
I have created a XML file as datasource which i 'm binding to a grid view control. During runtime I'm capturing items in XML file and displaying in a GRID VIEW control. but i want to remove or...
2
by: Umeshnath | last post by:
Hi, I have placed a grid view inside Atlas panel. On click of a button event, data is populated in the grid view, I want to add scroll bar instead of increasing the size of grid view. I have...
0
by: probashi | last post by:
I have a grid view control showing some records. I want to insert a blank line after each group of records. Any Idea.
3
by: Andrew Robinson | last post by:
I have a Grid View and associated Object Data Source control. The ODS interface with a custom data source that returns a List<MyEntity>. I am only referencing some of the columns on the GridView....
12
by: brwalias | last post by:
Hi, using .net 2 sql server 2005 Here is my situation: I'm passing a variable in the url from a selection on Page A and need to display the results on the Results page be based on that...
5
by: sspost | last post by:
i used Grid view and here is the code i wrote: Protected Sub ButtonAddFile_Click(ByVal sender As Object, ByVal e As EventArgs) Dim gv As New GridView gv.Style.Add("position",...
4
by: kavithadv | last post by:
hi Please help me i want to fix a column in grid view i used style for locking the column since i am setting the position as relative its not working properly i have given my code below ...
3
by: mvmashraf | last post by:
The simplest way i follows........... step 1: place the grid view in a DIV tag... ie: eg: <div id="divdatagrid" style="overflow: scroll; width: 750px; height: 265px"> Step 2 : on...
1
by: rani g | last post by:
whenever we insert a new row into the grid view control then existing view will be move down and new row will be added onto the the existing .
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.