Hi Jim,
I couldn't find any direct way to do what you want. However, I did find a
workaround using a hidden field. Here's my sample code which uses the Pubs
database.
The HTML
A grid with one template column & a button in the footer template of that
column. Then a hidden field named "h" with runat=server.
<form id="Form1" method="post" runat="server">
<asp:DataGrid id="DataGrid1" runat="server" ShowFooter="True">
<Columns>
<asp:TemplateColumn>
<FooterTemplate>
<asp:Button id="Button1" runat="server"
Text="Button"></asp:Button>
</FooterTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid><INPUT type="hidden" id="h" runat="server">
</form>
The Code-Behind
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Bind()
Else
Response.Write(h.Value)
h.Value = ""
End If
End Sub
Private Sub Bind()
Dim Qry1 As System.Data.SqlClient.SqlDataReader
Dim connectionString As String = "server='localhost';
trusted_connection=true; Database='pubs'"
Dim sqlConnection As System.Data.SqlClient.SqlConnection = New
System.Data.SqlClient.SqlConnection(connectionStri ng)
Dim queryString As String = "SELECT au_id, au_lname, au_fname FROM
authors"
Dim sqlCommand As System.Data.SqlClient.SqlCommand = New
System.Data.SqlClient.SqlCommand(queryString, sqlConnection)
sqlConnection.Open()
Qry1 =
sqlCommand.ExecuteReader(System.Data.CommandBehavi or.CloseConnection)
DataGrid1.DataSource = Qry1
DataGrid1.DataBind()
Qry1.Close()
sqlCommand.Dispose()
sqlConnection.Close()
sqlConnection.Dispose()
End Sub
Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.DataGridItemEventArgs) Handles
DataGrid1.ItemDataBound
If e.Item.ItemType = ListItemType.Footer Then
CType(e.Item.Cells(0).Controls(1),
WebControls.Button).Attributes.Add("onclick", "document.all('h').value =
'click'")
End If
End Sub
Thank you, Mike
Microsoft, ASP.NET Support Professional
Microsoft highly recommends to all of our customers that they visit the
http://www.microsoft.com/protect site and perform the three straightforward
steps listed to improve your computer’s security.
This posting is provided "AS IS", with no warranties, and confers no rights.
--------------------[color=blue]
> Content-Class: urn:content-classes:message
> From: "Jim Heavey" <anonymous@discussions.microsoft.com>
> Sender: "Jim Heavey" <anonymous@discussions.microsoft.com>
> References: <0eba01c3a9ec$9945a480$a101280a@phx.gbl>[/color]
<FNcp6vhqDHA.1548@cpmsftngxa06.phx.gbl>[color=blue]
> Subject: RE: DataGrid - Adding Rows
> Date: Thu, 13 Nov 2003 12:01:36 -0800
> Lines: 461
> Message-ID: <031201c3aa20$f195af20$a301280a@phx.gbl>
> MIME-Version: 1.0
> Content-Type: text/plain;
> charset="iso-8859-1"
> Content-Transfer-Encoding: 7bit
> X-Newsreader: Microsoft CDO for Windows 2000
> X-MIMEOLE: Produced By Microsoft MimeOLE V5.50.4910.0300
> Thread-Index: AcOqIPGTqfIjfLQnRFuR4w0rvk/WVA==
> Newsgroups: microsoft.public.dotnet.framework.aspnet
> Path: cpmsftngxa06.phx.gbl
> Xref: cpmsftngxa06.phx.gbl microsoft.public.dotnet.framework.aspnet:190753
> NNTP-Posting-Host: TK2MSFTNGXA11 10.40.1.163
> X-Tomcat-NG: microsoft.public.dotnet.framework.aspnet
>
> Thanks, but I was not looking for an example of how to
> add a row to the datasource, but rather, I was looking
> for how to trigger the adding of a row. I realize that I
> could add a button to the form, but I thought it would be
> much more visually appealing to add a button to the
> footer and my question was how to do this.
>
> Sorry for the confusion.[color=green]
> >-----Original Message-----
> >Hi Jim,
> >
> >There's an article that addresses this subject.
> >
> >Top Questions about the DataGrid Web Server Control
> >
http://msdn.microsoft.com/library/en-[/color]
> us/dv_vstechart/html/vbtchTopQuestionsA[color=green]
> >boutASPNETDataGridServerControl.asp
> >
> >Here is the relevant section.
> >
> >Adding Columns Dynamically
> >You can hide and show columns if you know in advance[/color]
> what columns you need.[color=green]
> >Sometimes, however, you do not know that until run time.[/color]
> In that case, you[color=green]
> >can create columns dynamically and add them to the grid.
> >
> >To do so, you create an instance of one of the column[/color]
> classes supported by[color=green]
> >the grid - BoundColumn, EditCommandColumn, ButtonColumn,[/color]
> or[color=green]
> >HyperlinkColumn. (You can add template columns to the[/color]
> grid, but it is[color=green]
> >slightly more complex. For details, see Creating Web[/color]
> Server Control[color=green]
> >Templates Programmatically.) Set the column's[/color]
> properties, and then add it[color=green]
> >to the grid's Columns collection.
> >
> >The following example shows how to add two bound columns[/color]
> to a grid.[color=green]
> >
> >' Visual Basic
> >Private Sub Button1_Click(ByVal sender As System.Object,[/color]
> _[color=green]
> > ByVal e As System.EventArgs) Handles Button1.Click
> > 'Set data-binding properties of the grid
> > DataGrid1.AutoGenerateColumns = False
> > DataGrid1.DataSource = Me.dsBooks1
> > DataGrid1.DataMember = "Books"
> > DataGrid1.DataKeyField = "bookid"
> >
> > ' Add two columns
> > Dim dgc_id As New BoundColumn()
> > dgc_id.DataField = "bookid"
> > dgc_id.HeaderText = "ID"
> > dgc_id.ItemStyle.Width = New Unit(80)
> > DataGrid1.Columns.Add(dgc_id)
> >
> > Dim dgc_title As New BoundColumn()
> > dgc_title.DataField = "title"
> > dgc_title.HeaderText = "Title"
> > DataGrid1.Columns.Add(dgc_title)
> >
> > Me.SqlDataAdapter1.Fill(Me.dsBooks1)
> > DataGrid1.DataBind()
> >End Sub
> >
> >// C#
> >private void Button1_Click(object sender,[/color]
> System.EventArgs e)[color=green]
> >{
> > DataGrid1.AutoGenerateColumns = false;
> > DataGrid1.DataSource = this.dsBooks1;
> > DataGrid1.DataMember = "Books";
> > DataGrid1.DataKeyField = "bookid";
> >
> > // Add two columns
> > BoundColumn dgc_id = new BoundColumn();
> > dgc_id.DataField = "bookid";
> > dgc_id.HeaderText = "ID";
> > dgc_id.ItemStyle.Width = new Unit(80);
> > DataGrid1.Columns.Add(dgc_id);
> >
> > BoundColumn dgc_title= new BoundColumn();
> > dgc_title.DataField = "title";
> > dgc_title.HeaderText = "Title";
> > DataGrid1.Columns.Add(dgc_title);
> >
> > this.sqlDataAdapter1.Fill(this.dsBooks1);
> > DataGrid1.DataBind();
> >}
> >Any time that you add controls to a page dynamically,[/color]
> you have the problem[color=green]
> >of persistence. Dynamically-added controls (or in this[/color]
> case, columns) are[color=green]
> >not automatically added to the page's view state, so you[/color]
> are obliged to add[color=green]
> >logic to the page to make sure the columns are available[/color]
> with each round[color=green]
> >trip.
> >
> >An excellent way to do this is to override the page's[/color]
> LoadViewState method,[color=green]
> >which gives you an early opportunity to reestablish[/color]
> columns in the DataGrid[color=green]
> >control. Because the LoadViewState method is called[/color]
> before the Page_Load[color=green]
> >event is raised, re-adding columns in the LoadViewState[/color]
> method assures that[color=green]
> >they are available for normal manipulation by the time[/color]
> any event code runs.[color=green]
> >
> >The following example shows how you would expand the[/color]
> previous example to[color=green]
> >restore the columns each time the page runs again. As[/color]
> before, the[color=green]
> >Button1_Click handler adds two columns to the grid. (In[/color]
> this example, the[color=green]
> >event handler calls a separate routine called AddColumns[/color]
> to do so.) In[color=green]
> >addition, the page contains a simple Boolean property[/color]
> called[color=green]
> >DynamicColumnsAdded indicating whether the grid has had[/color]
> columns added; the[color=green]
> >property persists its value in view state. The[/color]
> LoadViewState method first[color=green]
> >calls the base class's LoadViewState method, which[/color]
> extracts view state[color=green]
> >information and configures controls with it. If columns[/color]
> were previously[color=green]
> >added to the grid (as per the DynamicColumnsAdded[/color]
> property), the method[color=green]
> >then re-adds them.
> >
> >' Visual Basic
> >Private Property DynamicColumnAdded() As Boolean
> > Get
> > If ViewState("ColumnAdded") Is Nothing Then
> > Return False
> > Else
> > Return True
> > End If
> > End Get
> > Set(ByVal Value As Boolean)
> > ViewState("ColumnAdded") = Value
> > End Set
> >End Property
> >
> >Protected Overrides Sub LoadViewState(ByVal savedState[/color]
> As Object)[color=green]
> > MyBase.LoadViewState(savedState)
> > If Me.DynamicColumnAdded Then
> > Me.AddColums()
> > End If
> >End Sub
> >
> >Private Sub Button1_Click(ByVal sender As System.Object,[/color]
> _[color=green]
> > ByVal e As System.EventArgs) Handles Button1.Click
> > ' Check property to be sure columns are not added[/color]
> more than once[color=green]
> > If Me.DynamicColumnAdded Then
> > Return
> > Else
> > Me.AddColums()
> > End If
> >End Sub
> >
> >Protected Sub AddColums()
> > ' Add two columns
> > Dim dgc_id As New BoundColumn()
> > dgc_id.DataField = "instock"
> > dgc_id.HeaderText = "In Stock?"
> > dgc_id.ItemStyle.Width = New Unit(80)
> > DataGrid1.Columns.Add(dgc_id)
> >
> > Dim dgc_title As New BoundColumn()
> > dgc_title.DataField = "title"
> > dgc_title.HeaderText = "Title"
> > DataGrid1.Columns.Add(dgc_title)
> > Me.DataGrid1.DataBind()
> > Me.DynamicColumnAdded = True
> >End Sub
> >
> >// C#
> >private bool DynamicColumnAdded{
> > get
> > {
> > object b = ViewState["DynamicColumnAdded"];
> > return (b == null) ? false : true;
> > }
> > set
> > {
> > ViewState["DynamicColumnAdded"] = value;
> > }
> >}
> >
> >protected override void LoadViewState(object savedState)
> >{
> > base.LoadViewState(savedState);
> > if (DynamicColumnAdded)
> > {
> > this.AddColumns();
> > }
> >}
> >
> >private void Button1_Click(object sender,[/color]
> System.EventArgs e)[color=green]
> >{
> > if(this.DynamicColumnAdded != true)
> > {
> > this.AddColumns();
> > }
> >}
> >
> >private void AddColumns()
> >{
> > BoundColumn dgc_id = new BoundColumn();
> > dgc_id.DataField = "bookid";
> > dgc_id.HeaderText = "ID";
> > dgc_id.ItemStyle.Width = new Unit(80);
> > DataGrid1.Columns.Add(dgc_id);
> >
> > BoundColumn dgc_title= new BoundColumn();
> > dgc_title.DataField = "title";
> > dgc_title.HeaderText = "Title";
> > DataGrid1.Columns.Add(dgc_title);
> >
> > this.sqlDataAdapter1.Fill(this.dsBooks1);
> > DataGrid1.DataBind();
> > this.DynamicColumnAdded = true;
> >}
> >Adding New Records to a Data Source Using the DataGrid[/color]
> Control[color=green]
> >The DataGrid control allows users to view and edit[/color]
> records, but does not[color=green]
> >inherently include the facility to add new ones.[/color]
> However, you can add this[color=green]
> >functionality in various ways, all of which involve the[/color]
> following:[color=green]
> >
> >Adding a new, blank record to the data source of the[/color]
> grid (in the dataset[color=green]
> >or database). If necessary, you will need to assign an[/color]
> ID for the record[color=green]
> >and put placeholder values into it for any columns that[/color]
> cannot be null.[color=green]
> >Rebinding the DataGrid control to the source.
> >Putting the grid into edit mode for the new record. You[/color]
> need to be able to[color=green]
> >determine where in the grid the new record appears.
> >Updating the record normally when the user clicks[/color]
> Update, thereby writing[color=green]
> >the new record to the source with user-provided values.
> >The following example shows the process for adding the[/color]
> new record, binding[color=green]
> >the grid, and putting it into edit mode. In this[/color]
> example, the data source[color=green]
> >is a dataset (DsBooks1 or dsBooks1) containing a table[/color]
> called "Books."[color=green]
> >
> >' Visual Basic
> >Private Sub btnAddRow_Click(ByVal sender As[/color]
> System.Object, _[color=green]
> > ByVal e As System.EventArgs) Handles[/color]
> btnAddRow.Click[color=green]
> > Dim dr As DataRow = Me.DsBooks1.Books.NewRow
> > dr("title") = "(New)"
> > dr("instock") = True
> > Me.DsBooks1.Books.Rows.InsertAt(dr, 0)
> > Session("DsBooks") = DsBooks1
> > DataGrid1.EditItemIndex = 0
> > DataGrid1.DataBind()
> >End Sub
> >
> >// C#
> >private void btnAddRow_Click(object sender,[/color]
> System.EventArgs e)[color=green]
> >{
> > DataRow dr = this.dsBooks1.Books.NewRow();
> > dr["title"] = "(New)";
> > dr["instock"] = true;
> > this.dsBooks1.Books.Rows.InsertAt(dr, 0);
> > Session["DsBooks"] = dsBooks1;
> > DataGrid1.EditItemIndex = 0;
> > DataGrid1.DataBind();
> >}
> >Some things to notice:
> >
> >This code runs when a user clicks an Add button[/color]
> somewhere in the page.[color=green]
> >The new row is created using the NewRow method. It is[/color]
> then inserted into[color=green]
> >the dataset table using the InsertAt method, which[/color]
> allows you to place it[color=green]
> >at a specific, predefined location - in this case, as[/color]
> the first record in[color=green]
> >the table (that is, the first record in the Rows[/color]
> collection).[color=green]
> >Alternatively, you could add it to the end of the table,[/color]
> using the row[color=green]
> >count as the value. The important thing is that you know[/color]
> exactly where the[color=green]
> >row is in the table.
> >Because you know that the record is in the first[/color]
> position of the table, you[color=green]
> >can set the grid's EditItemIndex value to zero to put[/color]
> the new row into edit[color=green]
> >mode. (If you created the row elsewhere in the table,[/color]
> you would set[color=green]
> >EditItemIndex to that location instead.)
> >Because you have a new record in the dataset (but not[/color]
> yet in the database),[color=green]
> >you have to keep a copy of the dataset between round[/color]
> trips - you do not[color=green]
> >want to refill it from the database and lose the new[/color]
> record. Here, the code[color=green]
> >stores it in Session state. You need to reload the[/color]
> dataset from Session[color=green]
> >state when the page loads. The following example shows[/color]
> what your Page_Load[color=green]
> >handler might look like:
> >' Visual Basic
> >Private Sub Page_Load(ByVal sender As System.Object, _
> > ByVal e As System.EventArgs) Handles MyBase.Load
> > If Me.IsPostBack Then
> > DsBooks1 = CType(Session("DsBooks"), dsBooks)
> > Else
> > Me.SqlDataAdapter1.Fill(Me.DsBooks1)
> > Session("DsBooks") = DsBooks1
> > DataGrid1.DataBind()
> > End If
> >End Sub
> >
> >// C#
> >private void Page_Load(object sender, System.EventArgs e)
> >{
> > if(this.IsPostBack)
> > {
> > dsBooks1 = (dsBooks) Session["DsBooks"];
> > }
> > else
> > {
> > this.sqlDataAdapter1.Fill(this.dsBooks1);
> > Session["DsBooks"] = dsBooks1;
> > this.DataGrid1.DataBind();
> > }
> >}
> >For information about maintaining state, see Web Forms[/color]
> State Management in[color=green]
> >the Visual Studio documentation.
> >
> >You can update the record normally. For an example, see[/color]
> Walkthrough: Using[color=green]
> >a DataGrid Web Control to Read and Write Data in the[/color]
> Visual Studio[color=green]
> >documentation. After updating the dataset, update the[/color]
> database, then[color=green]
> >refresh the dataset. Be sure to save the refreshed[/color]
> dataset to Session state[color=green]
> >again. Here is an example of an update handler:
> >
> >' Visual Basic
> >Private Sub DataGrid1_UpdateCommand(ByVal source As[/color]
> Object, _[color=green]
> > ByVal e As[/color]
> System.Web.UI.WebControls.DataGridCommandEventArgs ) _[color=green]
> > Handles DataGrid1.UpdateCommand
> > Dim dr As Dataset.BooksRow
> > 'Get a reference to row zero (where the row was[/color]
> inserted)[color=green]
> > dr = Me.DsBooks1.Books(0)
> > Dim tb As TextBox = CType(e.Item.Cells(2).Controls[/color]
> (0), TextBox)[color=green]
> > dr.title = tb.Text
> > Dim cb As CheckBox = CType(e.Item.Cells(3).Controls[/color]
> (1), CheckBox)[color=green]
> > dr.instock = cb.Checked
> > Me.SqlDataAdapter1.Update(Me.DsBooks1)
> > DataGrid1.EditItemIndex = -1
> > 'Refresh the dataset from the database
> > DsBooks1.Clear()
> > Me.SqlDataAdapter1.Fill(Me.DsBooks1)
> > 'Save the refreshed dataset in Session state agin
> > Session("DsBooks") = DsBooks1
> > DataGrid1.DataBind()
> >End Sub
> >
> >// C#
> >private void DataGrid1_UpdateCommand(object source,
> > System.Web.UI.WebControls.DataGridCommandEventArgs[/color]
> e)[color=green]
> >{
> > dsBooks.BooksRow dr;
> > //Get a reference to row zero (where the row was[/color]
> inserted)[color=green]
> > dr = this.dsBooks1.Books[0];
> > TextBox tb1 = (TextBox) e.Item.Cells[2].Controls[0];
> > dr.title = tb1.Text;
> > CheckBox cb = (CheckBox) e.Item.Cells[3].Controls[1];
> > dr.instock = cb.Checked;
> > this.sqlDataAdapter1.Update(this.dsBooks1);
> > DataGrid1.EditItemIndex = -1;
> > //Refresh the dataset from the database
> > dsBooks1.Clear();
> > this.sqlDataAdapter1.Fill(this.dsBooks1);
> > //Save the refreshed dataset in Session state agin
> > Session["DsBooks"] = dsBooks1;
> > DataGrid1.DataBind();
> >}
> >
> >
> >Thank you, Mike
> >Microsoft, ASP.NET Support Professional
> >
> >Microsoft highly recommends to all of our customers[/color]
> that they visit the[color=green]
> >
http://www.microsoft.com/protect site and perform the[/color]
> three straightforward[color=green]
> >steps listed to improve your computer's security.
> >
> >This posting is provided "AS IS", with no warranties,[/color]
> and confers no rights.[color=green]
> >
> >
> >--------------------[color=darkred]
> >> Content-Class: urn:content-classes:message
> >> From: "Jim Heavey"[/color][/color]
> <anonymous@discussions.microsoft.com>[color=green][color=darkred]
> >> Sender: "Jim Heavey"[/color][/color]
> <anonymous@discussions.microsoft.com>[color=green][color=darkred]
> >> Subject: DataGrid - Adding Rows
> >> Date: Thu, 13 Nov 2003 05:46:54 -0800
> >> Lines: 5
> >> Message-ID: <0eba01c3a9ec$9945a480$a101280a@phx.gbl>
> >> MIME-Version: 1.0
> >> Content-Type: text/plain;
> >> charset="iso-8859-1"
> >> Content-Transfer-Encoding: 7bit
> >> X-Newsreader: Microsoft CDO for Windows 2000
> >> Thread-Index: AcOp7JlDGa9FRO6BRD68/L+nUe3T9Q==
> >> X-MimeOLE: Produced By Microsoft MimeOLE[/color][/color]
> V5.50.4910.0300[color=green][color=darkred]
> >> Newsgroups: microsoft.public.dotnet.framework.aspnet
> >> Path: cpmsftngxa06.phx.gbl
> >> Xref: cpmsftngxa06.phx.gbl[/color][/color]
> microsoft.public.dotnet.framework.aspnet:190635[color=green][color=darkred]
> >> NNTP-Posting-Host: TK2MSFTNGXA09 10.40.1.161
> >> X-Tomcat-NG: microsoft.public.dotnet.framework.aspnet
> >>
> >> Trying to figure out the technique which should be[/color][/color]
> used[color=green][color=darkred]
> >> 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?
> >>[/color]
> >
> >.
> >[/color]
>[/color]