How to define data used for DataGridview's column titles when using a list of objects in c#?
If you bind a DataGridview (winform) to a list of objects can you define which object property , a string, should be used for the column titles?
At the moment its using the properties names from the objects.
or is it possible to bind a separate datasource, another object, to the column headers for the purpose of defining these titles?
UDATE
Example
public string field_one{get;set;}
Shows up as "field_one" as the column header. I would like...
public string header_one{get;set;}
public string field_one{get;set;}
row.header_one="Friendly Header Title";
...........
List&l开发者_如何学运维t;row> rows = new List<row>();
So that the column header is "Friendly Header Title"
or to have a list of headers in a separate object, list of objects or other list based type.
example
class header...
{
...
public string header_column_one{get;set;}
..
}
....
class row....
{
...
public string field{get;set;}
..
}
....... ........
header.header_column_one="Nice Friendly Header"
List<row> rows = new List<row>();
Is this possible?
You can use the displayname attribute to customize the titles that will be displayed in the datagridview.
In your class, you can define each property like this
[DisplayName("Title")]
public string Something{get;set;}
Then "Title" will be shown as the header for this property in the grid. Using this way, you set the "default header" for all the datagrids in you app that are binded with a collection of this class.
EDIT:
Well, I think it will be difficult to change attributes in runtime, instead you can do something like
GridName.Columns["Something"].HeaderText = "Title"
EDIT2:
Ok, so you want to store the column name information in other class or object. Then you can try something like this
public static void ChangeHeaders(DataGridView dataGrid, Dictionary<String, String> data)
{
if (data == null)
{
return;
}
Dictionary<string, string>.Enumerator enumerator = data.GetEnumerator();
while (enumerator.MoveNext())
{
try
{
dataGrid.Columns[enumerator.Current.Key].HeaderText = enumerator.Current.Value;
}
catch (NullReferenceException e)
{
throw new ArgumentException("The column " + enumerator.Current.Key + " does not exist");
}
}
}
This function receives a datagridview object, and a dictionary of strings/strings. The key of the dictionary is the name of the property, and the value is the text you want in the header. Construct the dictionary, call the function and the work is done.
If i'm reading your question right, you're asking about setting the titles for the columns. DataGridViewColumn's HeaderText is your ticket.
MSDN Search "DataGridViewColumn"
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.aspx
精彩评论