2012-07-18 45 views
0

有时候,我通常会创建一个类我想这样的数据的类型:有没有办法将一个类的特定值绑定到数据网格?

public class message{ 
    private string subject { get; set; } 
    private string message { get; set; } 
} 

这样一来,我可以绑定一个List<message>到DataGrid,改变DataPropertyName。但是,如果我碰巧给这个类添加了更多的自动属性,我的数据网格开始变得不合时宜,有时候我不只想要一些属性到数据网格。无论如何,我可以将datagrid绑定到仅选择DataPropertyName的值吗?

谢谢。

回答

2

如果你不想在你的数据网格中出现额外的列,为什么不从你的查询开始,也不要在SELECT子句中列出它们。这有助于减少网络流量。

从同一张表创建多个查询或视图,并在正确的时间根据需要使用正确的查询或视图。这是“上游”解决方案。

或者,

当AutoGenerateColumns属性被设置为true时,每一列 自动其DataPropertyName属性设置为在由所述 DataSource属性中指定的数据源的 属性或数据库列的名称。此绑定也可以手动执行, 当您只想显示数据源中可用的 属性或数据库列的子集时非常有用。在这样的 个案中,将AutoGenerateColumns属性设置为false,然后 手动添加每个DataGridViewColumn,将每个 DataPropertyName属性的值设置为要显示的 数据源中的属性或数据库列。

这是直接从MSDN,你应该在发布之前更彻底的研究一下。 http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.datapropertyname.aspx

+0

如果你简单地说设置'DataGridView.AutoGenerateColumns = false;'并提供了链接或任何其他额外的细节,那就简单多了。谢谢。 – 2012-07-18 19:36:35

+0

并不意味着冒犯或以过多的信息将你埋没于必要的信息,但我确实认为指出如果你想要一个精简的,响应式的应用程序,那么sql语句中的经济是需要谨慎的。你可以做到这一点,并且在想要缩小数据集的情况下,通过使用匿名类保持传统的体积较大的课程。 @Andreas Niedermair暗示了这一点。 – GrayFox374 2012-07-18 20:04:13

0

您可以创建一个提供DataView的方法。

说你有这样的事情:

public class message { 
    private string subject { get; set; } 
    private string message { get; set; } 
    private string otherValue { get; set; } 
} 

然后你就可以像这样添加一个方法来消息类:

public static DataView GetDataGridList(List<message> lstMessages) { 
    DataTable dt = new DataTable(); 
    // Add the columns here for whatever properties you want 
    dt.Columns.Add("subject"); 
    dt.Columns.Add("message"); 

    foreach (message msg in lstMessages) { 
     DataRow dr = dt.NewRow(); // I think that's the call, I'm doing this off the top of my head, sorry. 
     dr["subject"] = msg.subject; 
     dr["message"] = msg.message; 
    } 

    return (dt.DefaultView); 
} 

然后,当你创建你的DataGrid,只要绑定像这样:

List<message> lstMessages = new List<message>(); 
// Populate the list however you want here. 
DataGrid dg = new DataGrid(); 
dg.DataSource = message.GetDataGridList(List<message>); 

你应该很好走。只要记住如果你改变了你想要的属性,把列添加到DataTable中,然后在foreach循环中。

+0

为什么不去一个匿名类型与linq-select结合?更容易! – 2012-07-18 18:03:45

相关问题