更改asp:GridView * autogenerated *列的顺序

时间:2013-10-01 15:52:47

标签: c# asp.net gridview .net-4.0

首先让我说我在StackOverflow上看到过类似的问题,但是我没见过任何专门针对自动生成列的问题。

我有asp:GridView我绑定到IEnumerable<Data>,其中Data可能会因运行时输入而异。但是,每个Data类共享几个基本属性:

public class BaseData
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class AddressData : BaseData
{
    public string Street1 { get; set; }
    public string Street2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; };
}

public class ContactData : BaseData
{
    public string Phone { get; set; }
    public DateTime LastUpdated { get; set; }
    // tons more public properties...
}

// More classes with lots of different public properties...

这些不同的类由数据库查询填充,因此我想在将数据放入GridView时自动生成列,因为有大量不同的字段。但是,我想首先显示共享基类中的列。如果我只是将IEnumerable<Data>分配给GridView数据源,则基类属性最后添加到GridView的列中。我试着纠正这样的情况:

// Callback after getting data from database
public void SetGridView<Data>(IEnumerable<Data> rows) where Data : BaseData
{
    // Make sure these columns show up first
    BoundField ID = new BoundField() { HeaderText = "ID", DataField = "ID" };
    BoundField Name = new BoundField() { HeaderText = "Name", DataField = "Name" };
    myGridView.Columns.Clear();
    myGridView.Columns.Add(ID);
    myGridView.Columns.Add(Name);
    myGridView.AutoGenerateColumns = true;
    myGridView.DataSource = rows;
    myGridView.DataBind();
}

但是,这只是重复开头和结尾的列,所以标题如下所示:

ID    Name    Street1    Street2    City    State    ZipCode    ID    Name

那么有没有办法让我将我知道的那些列(基类)移动到GridView列的开头,同时仍然可以自动生成所有其他列?

1 个答案:

答案 0 :(得分:1)

由于您被迫使用自动生成的列,我只需创建一个中间DataTable来绑定GridView。在该DataTable对象中,您可以按自己喜欢的顺序添加列。然后,GridView应以相同的顺序绑定。

修改: 修改BaseData,添加以下内容:

private DataTable dataForDisplay;

// This would be overridden by all child classes, adding their columns in the order you want
public virtual DataTable GetDataForDisplay()
{
    dataForDisplay = new DataTable();
    dataForDisplay.Columns.Add("ID");
    dataForDisplay.Columns.Add("Name");
    // If you want to change the order, just don't call the base.GetDataForDisplay()

    dataForDisplay.Rows.AddRange(this.ID, this.Name);

    return dataForDisplay;
}

然后所有其他子类都将覆盖GetDataForDisplay()