是否可以在C#ASP中以编程方式向GridView添加行?
如果是,怎么样?
我想直接从代码添加静态数据,而不是从数组或数据源
添加答案 0 :(得分:13)
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
dr["Column1"] = string.Empty;
dt.Rows.Add(dr);
然后,您可以将GridView
绑定到DataTable
...
gv.DataSource = dt;
gv.DataBind();
答案 1 :(得分:2)
dataGridView1.Columns[0].Name = "column1";
dataGridView1.Columns[1].Name = "column2";
string[] row1 = new string[] { "column1 value", "column2 value" };
dataGridView1.Rows.Add(row1);
答案 2 :(得分:1)
GridViewRowsCollection没有.Add
方法,因此您无法直接对GridView执行此操作。
还有其他选择。例如,如果将其绑定到DataTable - 您可以将包含数据的自定义行添加到DataTable。
另一种选择 - 通过在呈现的HTML表中添加一行来在客户端上执行此操作。
答案 3 :(得分:0)
可以在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);
}
答案 4 :(得分:-1)
我仍然建议您使用绑定/数据源,但当然您不必这样做。以下应该做你想要的:
DataGridViewTextBoxColumn columntype = new DataGridViewTextBoxColumn();
columntype.HeaderText = "Type";
columntype.Width = 80;
dataGridView1.Columns.Add(columntype);