[RESOLVED] Adding rows to GridView programatically
Today is the first day i hav to use the new ASP.NET 2.0 GridView control. After searching all over the place, it seems that one cannot programatically add rows to GridView like one can with DataGrid. Why can`t i add rows programatically? And is it possible with some trick to add rows? Makes me feel like wanting to go back to using DataGrid
Re: Adding rows to GridView programatically
You can populate a 'DataTable' with your data then bind that to the gridview (you can programatically add rows to the datatable).
i.e
Code:
Imports System.Data
Private Sub BindData()
gridview1.DataSource = GetData()
gridview1.DataBind()
End Sub
Protected Function FormatDataTable() as DataTable
Dim dt as DataTable = New DataTable()
' Create Columns
dt.Columns.Add("id", System.Type.GetType("System.String"))
dt.Columns.Add("text", System.Type.GetType("System.String"))
Return dt
End Function
Protected Function GetData() as DataTable
Dim dt as DataTable = FormatDataTable()
Dim dr as DataRow
' Populate the datatable with your data (put this in appropriate loop)
dr = dt.NewRow
dr("id") = "1"
dr("txt") = "Hi"
' Add the row
dt.Rows.Add(dr)
dt.AcceptChanges
Return dt
End Function
;)
Re: Adding rows to GridView programatically
this's the link
http://www.codeproject.com/aspnet/NewRowGridView.asp
you can use a botton and add rows
if you change this parth:
public void CreateNewRows()
{
if (this.NewRowCount > 0)
{
ArrayList list = new ArrayList();
DataControlField[] fields = this.GetDataControlFields();
for (int i = 0; i < this.NewRowCount; i++)
{
GridViewRow newRow = this.CreateNewRow(i, fields);
list.Add(newRow);
}
this._newRows = new GridViewRowCollection(list);
Table grid;
int rowIndex;
if (this.Rows.Count == 0)
{
grid = this.CreateChildTable();
this.Controls.Add(grid);
if (this.ShowHeader)
{
GridViewRow headerRow = this.CreateHeaderRow(fields);
grid.Rows.Add(headerRow);
}
rowIndex = this.Rows.Count + 1;
}
else
{
grid = this.CreateChildTable();
rowIndex = 0;
}
foreach (GridViewRow newRow in this._newRows)
{
grid.Rows.AddAt(rowIndex, newRow);
rowIndex++;
}
this.Controls.Add(grid);
}
}
in c#:
public static int intContador; (attribute)
protected void btnAgregar_Click(object sender, ImageClickEventArgs e)
{
intContador++;
GridView1.NewRowCount = intContador;
}