473,703 Members | 2,294 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Adding rows to a DataGrid in a web form

I have a DataGrid on a webform bound to a Datasource and can
successfully use <ItemTemplate > to create edit/update/cancel
functionality for user maintenance of data. I use separate logic to
delete a row. Everything works just fine.

BUT

I would like to add a button to (for example) the DataGrid header, which
when pressed will add a new row to the datagrid. This should then allow
the user to enter information into text boxes (in some columns) or
select from a dropdownlist (in other columns).

Once the user clicks "Add" for the newly created row, the data will then
be written back to the backend.

How can I add rows to the DataGrid based upon this button click event?
What parameters are passed to the handling routine? It seems that adding
new rows to a DataGrid is quite difficult. I would have expected an
.AddRow() method to exist but it does not seem to...

Many thanks for any ideas/sample code.

Regards,
Clayton

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #1
2 3636
Hi Clayton,

How can I add rows to the DataGrid based upon this button click event?
What parameters are passed to the handling routine? It seems that adding
new rows to a DataGrid is quite difficult. I would have expected an
AddRow() method to exist but it does not seem to...


It does not exist cause the DataGrid is only mean as a way to display data,
not to keep it, therefore if you want to add a row you have to add a row to
the datasource.
I will show you a complete example of one of my projects, I'm not binding
again a dataset but again a strong typed collection but you can change that
and have the same functionality but in the code you will find classes that
you don't know.
aspx code:
this is how I declare the grid in the page:
I use TemplateColumns cause I feel more free using them, or maybe is cause I
have always use them :)
GetDataGridSour ce() is a method that return the datasource , I do it so
cause the source can change depending of other controls in the page.

I declare the columns as you can see the way I want it to look, the first
column contain the ID of the record I'm showing therefore its Visible
property is false

If you see the second column it define two sections ItemTemplate and
EditItemTemplat e the latter is only used when that row is the one being
edited. In that row I'm using a DropDownList that is also databounded.

Finally the third column is where the buttons are located, here I have two
Edit/Delete that do that the name imply.
I also have a Add button, but it's located outside the grid and is not
shown in here, if you still have problem post back and I will post that part
too.

<asp:datagrid id=recordgrid runat="server" ShowHeader="fal se"
autoGenerateCol umns="False" DataSource="<%# GetDataGridSour ce()%>"
OnEditCommand=" RecordEditComma nd" OnDeleteCommand ="RecordDeleteC ommand">

<columns>
<asp:templateco lumn Visible="False" >
<itemtemplate >
<asp:Label Visible="False" id="recordID" Runat="server"
Text='<%# ((CtpRecord)Con tainer.DataItem ).ID.ToString() %>'>
</asp:Label>
</itemtemplate>
</asp:templatecol umn>
<asp:templateco lumn ItemStyle-VerticalAlign=" Top"
ItemStyle-Width="140" ItemStyle-HorizontalAlign ="left"
ItemStyle-Cssclass="textB old">
<itemtemplate >
<asp:Label CssClass="text" Runat="server" Text='<%#
((CtpLocationDe tail)Container. DataItem).RoadN umber%>' ID="Label3">
</asp:Label>
</itemtemplate>
<EditItemTempla te>
<asp:DropDownLi st OnSelectedIndex Changed="Update LocationMinor"
AutoPostBack="T rue" ID="locationdrp " Runat="server" DataSource="<%#
CtpLocation.Loc ations%>" DataTextField=" LocationUID" DataValueField= "ID">
</asp:DropDownLis t>
</EditItemTemplat e>
</asp:templatecol umn>
<asp:templateco lumn ItemStyle-VerticalAlign=" Top"
ItemStyle-Width="80" ItemStyle-HorizontalAlign ="right"
ItemStyle-Cssclass="textB old">
<itemtemplate >
<asp:imagebutto n ToolTip="Edit Action" runat="server"
CommandName="Ed it" Visible="<%# CanEditAction(
(CtpAction)Cont ainer.DataItem )%>" ImageUrl="image s/ico_edit.gif"
ID="Imagebutton 5" />
<asp:imagebutto n ToolTip="Delete Action" runat="server"
CommandName="De lete" Visible="<%# CanDelAction(
(CtpAction)Cont ainer.DataItem )%>" ImageUrl="image s/ico_delete.gif"
ID="Imagebutton 3" /><br>
</itemtemplate>
</asp:templatecol umn>

Well basically that is the aspx code, now the cs code, I have to define a
Delete and a Edit function. Let's start by the Delete as it;s the easiest:
I use the ID keeped on the hidden column I found that element in the
collection and delete it then rebind the grid and voila the row is deleted.
protected void LocationDeleteC ommand(object sender, DataGridCommand EventArgs
e)

{

int locationID = Convert.ToInt32 (
((Label)e.Item. FindControl("Lo cationID")).Tex t);

CtpLocationDeta il l = record.Location s.Find( locationID);

record.Location s.Remove( l); //remove from the datasource

locationgrid.Da taBind(); //rebind it
}
The edit is almost as easy:
protected void LocationEditCom mand(object sender, DataGridCommand EventArgs
e)

{

locationgrid.Ed itItemIndex = e.Item.ItemInde x;

locationgrid.Da taBind();

}

Finally the Add():
It's as simple as adding a new record to the collection, set the
EditItemIndex to the correct record and rebind it. I usually insert the new
record at the start of the list.
here is the method: ( I'm using an ImageButton for the Add and that's why
the handler signature is different )
protected void AddLocation(obj ect sender, System.Web.UI.I mageClickEventA rgs
e)
{

CtpLocationDeta il newloc = new CtpLocationDeta il();
locationsCloned .Insert( 0, newloc);
this.locationgr id.EditItemInde x = 0;
LocationPanel.D ataBind();

}

I did not show you here the "save" operation where you get all the data you
entered and save it back to the datasource, if you need that too just let
me know

Hope this help,
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Nov 15 '05 #2

Hi Clayton,

You should add a new row to the dataset that bind to the datagrid.
Then when you click the button, you post back the command to the server
side and trigger the
dataset to add new row.
At last, you can bind the dataset to the datagrid again.

Hope this helps,
Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

--------------------
| From: Clayton Hamilton <cl*@who.dk>
| X-Newsreader: AspNNTP 1.50 (ActionJackson. com)
| Subject: Adding rows to a DataGrid in a web form
| Mime-Version: 1.0
| Content-Type: text/plain; charset="us-ascii"
| Content-Transfer-Encoding: 7bit
| Message-ID: <ej************ **@TK2MSFTNGP11 .phx.gbl>
| Newsgroups: microsoft.publi c.dotnet.langua ges.csharp
| Date: Mon, 29 Sep 2003 07:15:26 -0700
| NNTP-Posting-Host: actionjackson13 3.dsl.frii.net 216.17.147.133
| Lines: 1
| Path: cpmsftngxa06.ph x.gbl!TK2MSFTNG P08.phx.gbl!TK2 MSFTNGP11.phx.g bl
| Xref: cpmsftngxa06.ph x.gbl microsoft.publi c.dotnet.langua ges.csharp:1879 88
| X-Tomcat-NG: microsoft.publi c.dotnet.langua ges.csharp
|
| I have a DataGrid on a webform bound to a Datasource and can
| successfully use <ItemTemplate > to create edit/update/cancel
| functionality for user maintenance of data. I use separate logic to
| delete a row. Everything works just fine.
|
| BUT
|
| I would like to add a button to (for example) the DataGrid header, which
| when pressed will add a new row to the datagrid. This should then allow
| the user to enter information into text boxes (in some columns) or
| select from a dropdownlist (in other columns).
|
| Once the user clicks "Add" for the newly created row, the data will then
| be written back to the backend.
|
| How can I add rows to the DataGrid based upon this button click event?
| What parameters are passed to the handling routine? It seems that adding
| new rows to a DataGrid is quite difficult. I would have expected an
| .AddRow() method to exist but it does not seem to...
|
| Many thanks for any ideas/sample code.
|
| Regards,
| Clayton
|
| *** Sent via Developersdex http://www.developersdex.com ***
| Don't just participate in USENET...get rewarded for it!
|

Nov 15 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3129
by: Dave Elliott | last post by:
After inserting a new data row to a DataTable that is bound to a datagrid, I am unable to change data in a row that is after the newly added row without getting bizarre results. I have added the full code for the test below. Create a project drop in the code and run. Any help would be appreciated. Cheers,
2
10002
by: Jim | last post by:
In my Win App, I have a datagrid that's bound to a dataset. When the form loads, the datagrid fills. How can I add an empty row to the end of the datagrid during a button click (similar to pressing Tab when mouse pointer is on last field of last record of datagrid)? The datagrid's read-only so the user won't be able to modify it unless he wants to add a new record via the datagrid (by adding the empty row). Also, if I modify the...
0
1669
by: mgenti | last post by:
I am experiencing a problem when I add a row to a DataTable that is used on a DataGrid in my Windows Form application. When I add a new row I no longer get a response from my form. I see the row apear in the DataGrid but still no response from the form. If I add the same data to a rich text box and don't use the datagrid I don't have this problem. What am I missing? It has to be something simple. Here is my code snipet: private...
2
2706
by: Aaron Ackerman | last post by:
I cannot a row to this bound DataGrid to SAVE MY LIFE! I have tried everything and I am at a loss. The using goes into add mode with the add button adds his data then updates with the update button, seems simple. I am using ALL visual controls (supposedly to simplify things. If I was not using the visual controls and calling an ExecuteNonQuery no prob. Please look at my code and tell me what I am doing wrong. Also, what are the advatages...
3
4878
by: Jim Heavey | last post by:
Trying to figure out the technique which should be used to add rows to a datagrid. I am thinking that I would want an "Add" button on the footer, but I am not quite sure how to do that. Is that the best method? Do you have a sample of how to do this?
1
3288
by: Andrew | last post by:
Hey all, I am very new to ASP.Net (and .Net in general), but that isn't stopping the boss from wanting to begin new projects in it. This latest project has me kinda stumped and after a couple days of struggling, I figure asking you all (the experts) will keep me from going down some dark and dangerous road. The project I have is a fairly simple one, in theory anyway. The gist is to create a page where the user enters an IDNumber,...
2
1967
by: Praveen Balanagendra via .NET 247 | last post by:
here is the source code private void AddRow() { TableCell tc = new TableCell(); tc.Controls.Add(new LiteralControl("NewRow")); DataGridItem di = new DataGridItem(DataGrid1.Items.Count+1,DataGrid1.Items.Count+1,ListItemType.Item); di.Cells.Add(tc); di.Cells.Add(tc1);
2
3566
by: Flack | last post by:
Hey guys, I have a DataGrid and DataTable field in my class : private ImageDataGrid dataGrid1; //ImageDataGrid extends dataGrid and just overides OnMouseDown private DataTable dt = new DataTable("MyTable"); In the classes constructor, after InitializeComponent() I call the following
12
6215
by: JMO | last post by:
I can import a csv file with no problem. I can also add columns to the datagrid upon import. I want to be able to start importing at the 3rd row. This will pick up the headers necessary for the datagrid. Once I can get to that point I need some way to be able to add new data only to the new columns that were added. Here is some of my code: //Function For Importing Data From CSV File public DataSet ConnectCSV(string filetable)
0
8750
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9111
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8961
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6585
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5922
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4421
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3114
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2439
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2058
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.