Add row to grid view

前端 未结 5 2331
庸人自扰
庸人自扰 2021-02-14 08:28

Is it possible to programmatically add a row to a GridView in C# ASP?

If yes, how ?

I want to add static data directly from the code, not from an array nor an da

相关标签:
5条回答
  • 2021-02-14 08:33
    dataGridView1.Columns[0].Name = "column1";
    dataGridView1.Columns[1].Name = "column2";
    
    string[] row1 = new string[] { "column1 value", "column2 value" };
    dataGridView1.Rows.Add(row1);
    
    0 讨论(0)
  • 2021-02-14 08:40

    Rows can be inserted on GridView_RowCreated, Like

    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);
    }
    
    0 讨论(0)
  • 2021-02-14 08:41

    GridViewRowsCollection doesn't have .Add method, so you can't do it directly to the GridView.

    There're alternatives. For example if you bind it to a DataTable - you can add custom row with data to the DataTable.

    Another alternative - do it on client by adding a row to rendered HTML Table.

    0 讨论(0)
  • 2021-02-14 08:50
    DataTable dt = new DataTable();
    DataRow dr = dt.NewRow();
    dr["Column1"] = string.Empty;
    dt.Rows.Add(dr);
    

    You can then bind your GridView to the DataTable...

    gv.DataSource = dt;
    gv.DataBind();
    
    0 讨论(0)
  • 2021-02-14 08:56

    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);
    
    0 讨论(0)
提交回复
热议问题