我似乎在绕圈跑,并且在过去的几个小时里一直在这样做。
我想从一个字符串数组填充一个datagridview。我认为这是不可能的,我需要创建一个将字符串作为公共属性保存的自定义类型。所以我做了一个类:
public class FileName
{
private string _value;
public FileName(string pValue)
{
_value = pValue;
}
public string Value
{
get
{
return _value;
}
set { _value = value; }
}
}
这是container类,它只有一个带有字符串值的属性。现在,当我将数据源绑定到列表时,我只希望该字符串出现在datagridview中。
我还有这个方法,BindGrid(),我想用它填充datagridview。这就是它:
private void BindGrid()
{
gvFilesOnServer.AutoGenerateColumns = false;
//create the column programatically
DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn();
DataGridViewCell cell = new DataGridViewTextBoxCell();
colFileName.CellTemplate = cell; colFileName.Name = "Value";
colFileName.HeaderText = "File Name";
colFileName.ValueType = typeof(FileName);
//add the column to the datagridview
gvFilesOnServer.Columns.Add(colFileName);
//fill the string array
string[] filelist = GetFileListOnWebServer();
//try making a List<FileName> from that array
List<FileName> filenamesList = new List<FileName>(filelist.Length);
for (int i = 0; i < filelist.Length; i++)
{
filenamesList.Add(new FileName(filelist[i].ToString()));
}
//try making a bindingsource
BindingSource bs = new BindingSource();
bs.DataSource = typeof(FileName);
foreach (FileName fn in filenamesList)
{
bs.Add(fn);
}
gvFilesOnServer.DataSource = bs;
}
最后,问题是:字符串数组填充ok,列表创建ok,但我在datagridview中得到一个空列。我还直接尝试了datasource= list<>,而不是= bindingsource,仍然什么都没有。
我真的很感谢你的建议,这已经让我抓狂了。
发布于 2009-08-04 16:56:22
使用BindingList并设置列的DataPropertyName-Property。
尝试以下操作:
...
private void BindGrid()
{
gvFilesOnServer.AutoGenerateColumns = false;
//create the column programatically
DataGridViewCell cell = new DataGridViewTextBoxCell();
DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()
{
CellTemplate = cell,
Name = "Value",
HeaderText = "File Name",
DataPropertyName = "Value" // Tell the column which property of FileName it should use
};
gvFilesOnServer.Columns.Add(colFileName);
var filelist = GetFileListOnWebServer().ToList();
var filenamesList = new BindingList<FileName>(filelist); // <-- BindingList
//Bind BindingList directly to the DataGrid, no need of BindingSource
gvFilesOnServer.DataSource = filenamesList
}
发布于 2013-12-21 13:30:53
可能会有点晚,但对将来有用。如果您不需要设置单元格的自定义属性,而只关心标题文本和单元格的值,那么此代码将对您有所帮助
public class FileName
{
[DisplayName("File Name")]
public string FileName {get;set;}
[DisplayName("Value")]
public string Value {get;set;}
}
然后,您可以将列表作为数据源绑定为
private void BindGrid()
{
var filelist = GetFileListOnWebServer().ToList();
gvFilesOnServer.DataSource = filelist.ToArray();
}
欲了解更多信息,请访问此页面Bind List of Class objects as Datasource to DataGridView
希望这能对你有所帮助。
发布于 2015-11-19 03:02:32
我知道这是旧的,但这让我挂了好一阵子。列表中对象的属性必须是实际的“属性”,而不仅仅是公共成员。
public class FileName
{
public string ThisFieldWorks {get;set;}
public string ThisFieldDoesNot;
}
https://stackoverflow.com/questions/1228539
复制相似问题