将空行插入到asp:GridView中

时间:2015-03-04 19:43:31

标签: c# asp.net gridview

我有一个存储过程,它会带回一个绑定到ASP:GridView的记录集。如果该过程找不到应显示的数据并且不返回任何记录,我希望在ASP GridView中插入空白行,以便我可以访问行以分配行标题标签。此网格应具有静态行数,每个行包含BoundFields和TemplateFields。插入这些空行需要什么?

<asp:GridView ID="myGrid" runat="server" OnRowDataBound="myGrid_rowBound" AutoGenerateColumns="false" Width="100%">
      <Columns>
           <asp:TemplateField>
               <ItemTemplate>
                     <asp:Label ID="lblRowHeader" runat="server"</asp:Label>
               </ItemTemplate>
           </asp:TemplateField>
           <asp:BoundField DataField="AsOf" DataFormatString="{0:F1}" />
           <asp:TemplateField>
                <ItemTemplate>
                      <input type="text" ID="txtToHire" />
                      <asp:RegularExpressionValidator ID="rev" runat="server" ControlToValidate="txtToHire" Display="None" />
                </ItemTemplate>
           </asp:TemplateField>
           <asp:BoundField DataField="Current" DataFormatString="{0:F1}" />
           <asp:BoundField DataField="Guideline" DataFormatString="{0:F1}" />
      </Columns>
</asp:GridView>

代码背后:

// normal stored procedure call and binding
// ....

DataTable newSource = new DataTable();
if (myGrid.Rows.Count == 0)
{
    for (int i = 0; i < 2; i++)
    {
        DataRow dr = newSource.NewRow();
        newSource.Rows.InsertAt(dr, i);
    }

    myGrid.DataSource = newSource;
    myGrid.DataBind();
}

1 个答案:

答案 0 :(得分:0)

行没有绑定到GridView的原因不是因为行没有设置正确的列名,而是因为我没有将列添加到DataTable 。这段代码就是我所缺少的:

DataTable newSource = new DataTable();

newSource.Columns.Add("AsOf");
newSource.Columns.Add("Current");
newSource.Columns.Add("Guideline");

// Now programatically add the rows that I needed