11

是否可以在 C# ASP 中以编程方式向 GridView 添加一行?

如果是,如何?

我想直接从代码中添加静态数据,而不是从数组或数据源中

4

5 回答 5

15
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
dr["Column1"] = string.Empty;
dt.Rows.Add(dr);

然后,您可以将您的绑定GridViewDataTable...

gv.DataSource = dt;
gv.DataBind();
于 2013-10-08T20:22:55.013 回答
3
dataGridView1.Columns[0].Name = "column1";
dataGridView1.Columns[1].Name = "column2";

string[] row1 = new string[] { "column1 value", "column2 value" };
dataGridView1.Rows.Add(row1);
于 2013-10-08T20:22:08.950 回答
1

GridViewRowsCollection没有.Add方法,所以不能直接对 GridView 做。

还有其他选择。例如,如果您将其绑定到 DataTable - 您可以将带有数据的自定义行添加到 DataTable。

另一种选择 - 在客户端上通过向呈现的 HTML 表添加一行来执行此操作。

于 2013-10-08T20:21:28.137 回答
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);
}
于 2017-11-07T12:57:23.187 回答
-1

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);
于 2013-10-08T20:18:49.000 回答