【发布时间】:2010-11-16 17:52:37
【问题描述】:
我似乎在兜圈子,在过去的几个小时里一直在这样做。
我想从一个字符串数组中填充一个 datagridview。我已经阅读了它不可能直接,并且我需要创建一个将字符串作为公共属性保存的自定义类型。于是我做了一个类:
public class FileName
{
private string _value;
public FileName(string pValue)
{
_value = pValue;
}
public string Value
{
get
{
return _value;
}
set { _value = value; }
}
}
这是容器类,它只是有一个带有字符串值的属性。我现在想要的只是当我将它的数据源绑定到列表时,该字符串出现在 datagridview 中。
我也有这个方法,BindGrid(),我想用它来填充数据网格视图。这里是:
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;
}
最后,问题:字符串数组填充正常,列表创建正常,但我在datagridview中得到一个空列。我也直接试过datasource=list,而不是=bindingsource,还是什么都没有。
非常感谢您的建议,这让我发疯了。
【问题讨论】:
-
有一点需要注意,只有对象中那些作为属性的公共字段才会在网格中呈现。换句话说,他们需要有 { get;放; } 定义,否则它们将被忽略。
标签: c# .net binding datagridview