【问题标题】:Can you add data to a datagrid with no data source?您可以将数据添加到没有数据源的数据网格吗?
【发布时间】:2010-09-21 03:01:53
【问题描述】:

我有一个包含 5 个模板列的 DataGrid,

但是,当我尝试将一些动态创建的控件添加到网格中时,它会失败,因为没有行。

-我可以在其中添加一个空白行并使用它吗?如何? - 或者其他方式?

【问题讨论】:

    标签: c# asp.net datagrid controls


    【解决方案1】:

    我很确定您必须绑定到数据源。但是创建自己的DataTable 并在其中插入一行包含一些虚拟信息很容易。

    //pseudo code:
    
    DataTable dt = new DataTable();
    DataColumn dc = new DataColumn("column1");
    dt.Columns.Add(dc);
    DataRow dr = dt.NewRow();
    dr["column1"] = "value1";
    dt.Rows.AddNew(dr);
    
    myDataGrid.DataSource = dt;
    myDataGrid.DataBind();
    

    【讨论】:

      【解决方案2】:

      如果您使用的是未绑定的 DataGridView,则可以创建新行,然后将它们添加到 DataGridView。您的问题涉及 DataGrid,但您将其标记为 DataGridView。

      // Sample code to add a new row to an unbound DataGridView
      DataGridViewRow YourNewRow = new DataGridViewRow();
      
      YourNewRow.CreateCells(YourDataGridView);
      YourNewRow.Cells[0].Value = "Some value";
      YourNewRow.Cells[1].Value = "Another value";
      
      YourDataGridView.Rows.Add(YourNewRow);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 2014-08-30
        相关资源
        最近更新 更多