是否可以在 C# ASP 中以编程方式向 GridView 添加一行?
如果是,如何?
我想直接从代码中添加静态数据,而不是从数组或数据源中
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
dr["Column1"] = string.Empty;
dt.Rows.Add(dr);
然后,您可以将您的绑定GridView
到DataTable
...
gv.DataSource = dt;
gv.DataBind();
dataGridView1.Columns[0].Name = "column1";
dataGridView1.Columns[1].Name = "column2";
string[] row1 = new string[] { "column1 value", "column2 value" };
dataGridView1.Rows.Add(row1);
GridViewRowsCollection没有.Add
方法,所以不能直接对 GridView 做。
还有其他选择。例如,如果您将其绑定到 DataTable - 您可以将带有数据的自定义行添加到 DataTable。
另一种选择 - 在客户端上通过向呈现的 HTML 表添加一行来执行此操作。
可以插入行GridView_RowCreated
,例如
protected void gvItems_RowCreated(object sender, GridViewRowEventArgs e)
{
GridViewRow NewHeader = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert);
NewHeader.Font.Bold = true;
NewHeader.CssClass = "heading";
//Item#
TableCell NewHeaderCell = new TableCell();
NewHeaderCell.Text = "#";
NewHeaderCell.HorizontalAlign = HorizontalAlign.Left;
NewHeader.Cells.Add(NewHeaderCell);
//Item#
NewHeaderCell = new TableCell();
NewHeaderCell.Text = "Item#";
NewHeaderCell.HorizontalAlign = HorizontalAlign.Left;
NewHeader.Cells.Add(NewHeaderCell);
//Amount
NewHeaderCell = new TableCell();
NewHeaderCell.Text = "Amount";
NewHeaderCell.HorizontalAlign = HorizontalAlign.Right;
NewHeader.Cells.Add(NewHeaderCell);
GridView1.Controls[0].Controls.AddAt(e.Row.RowIndex +
rowIndex, NewHeader);
}
I still recommend that you use binding/datasource, but of course you don't have to. The following should do what you want:
DataGridViewTextBoxColumn columntype = new DataGridViewTextBoxColumn();
columntype.HeaderText = "Type";
columntype.Width = 80;
dataGridView1.Columns.Add(columntype);