473,394 Members | 1,956 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

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 3604
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 :)
GetDataGridSource() 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
EditItemTemplate 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="false"
autoGenerateColumns="False" DataSource="<%# GetDataGridSource()%>"
OnEditCommand="RecordEditCommand" OnDeleteCommand="RecordDeleteCommand">

<columns>
<asp:templatecolumn Visible="False">
<itemtemplate>
<asp:Label Visible="False" id="recordID" Runat="server"
Text='<%# ((CtpRecord)Container.DataItem).ID.ToString()%>'>
</asp:Label>
</itemtemplate>
</asp:templatecolumn>
<asp:templatecolumn ItemStyle-VerticalAlign="Top"
ItemStyle-Width="140" ItemStyle-HorizontalAlign="left"
ItemStyle-Cssclass="textBold">
<itemtemplate>
<asp:Label CssClass="text" Runat="server" Text='<%#
((CtpLocationDetail)Container.DataItem).RoadNumber %>' ID="Label3">
</asp:Label>
</itemtemplate>
<EditItemTemplate>
<asp:DropDownList OnSelectedIndexChanged="UpdateLocationMinor"
AutoPostBack="True" ID="locationdrp" Runat="server" DataSource="<%#
CtpLocation.Locations%>" DataTextField="LocationUID" DataValueField="ID">
</asp:DropDownList>
</EditItemTemplate>
</asp:templatecolumn>
<asp:templatecolumn ItemStyle-VerticalAlign="Top"
ItemStyle-Width="80" ItemStyle-HorizontalAlign="right"
ItemStyle-Cssclass="textBold">
<itemtemplate>
<asp:imagebutton ToolTip="Edit Action" runat="server"
CommandName="Edit" Visible="<%# CanEditAction(
(CtpAction)Container.DataItem )%>" ImageUrl="images/ico_edit.gif"
ID="Imagebutton5" />
<asp:imagebutton ToolTip="Delete Action" runat="server"
CommandName="Delete" Visible="<%# CanDelAction(
(CtpAction)Container.DataItem )%>" ImageUrl="images/ico_delete.gif"
ID="Imagebutton3" /><br>
</itemtemplate>
</asp:templatecolumn>

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 LocationDeleteCommand(object sender, DataGridCommandEventArgs
e)

{

int locationID = Convert.ToInt32(
((Label)e.Item.FindControl("LocationID")).Text);

CtpLocationDetail l = record.Locations.Find( locationID);

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

locationgrid.DataBind(); //rebind it
}
The edit is almost as easy:
protected void LocationEditCommand(object sender, DataGridCommandEventArgs
e)

{

locationgrid.EditItemIndex = e.Item.ItemIndex;

locationgrid.DataBind();

}

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(object sender, System.Web.UI.ImageClickEventArgs
e)
{

CtpLocationDetail newloc = new CtpLocationDetail();
locationsCloned.Insert( 0, newloc);
this.locationgrid.EditItemIndex = 0;
LocationPanel.DataBind();

}

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.public.dotnet.languages.csharp
| Date: Mon, 29 Sep 2003 07:15:26 -0700
| NNTP-Posting-Host: actionjackson133.dsl.frii.net 216.17.147.133
| Lines: 1
| Path: cpmsftngxa06.phx.gbl!TK2MSFTNGP08.phx.gbl!TK2MSFTN GP11.phx.gbl
| Xref: cpmsftngxa06.phx.gbl microsoft.public.dotnet.languages.csharp:187988
| X-Tomcat-NG: microsoft.public.dotnet.languages.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
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...
2
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...
0
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...
2
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...
3
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...
1
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...
2
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...
2
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...
12
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...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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...

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.