我有一个
Dictionary<string, string>
obejct,其数据应通过在
TextBox
控件,然后以
ListView
控制
我想出的解决方案是:
下面是我如何转换字典的:
static DataTable dtDepartments { get; set; }
static Dictionary<string, string> GetDepartments(string _depNum, out bool _isOff)
{
// retrieve the list from a SQL Server DB
}
public myForm()
{
InitializeComponent();
Dictionary<string, string> Departments = new Dictionary<string, string>();
Departments = GetDepartments(string.Empty, out bool _isOff);
dtDepartments = new DataTable();
dtDepartments.TableName = "DEPARTMENTS";
DataColumn idColumn = dtDepartments.Columns.Add("NUM", typeof(string));
dtDepartments.Columns.Add("NAME", typeof(string));
dtDepartments.PrimaryKey = new DataColumn[] { idColumn };
foreach(KeyValuePair<string,string> kvP in Departments)
{
dtDepartments.Rows.Add(new object[] { kvP.Key, kvP.Value });
}
}
这就是我在事件方法中填充列表的方式
private void txtFilter_TextChanged(object sender, EventArgs e)
{
string filter = "NAME LIKE '%" + txtFilter.Text + "%'";
DataRow[] foundRows = dtDepartments.Select(filter);
if (foundRows.Length > 0)
{
lvDepartments.Visible = true;
ResizeListView(foundRows.Length);
PopulateListView(foundRows);
}
}
void ResizeListView(int _rows)
{
lvDepartments.Height = Math.Min(25 + (20 * _rows), 205);
}
void PopulateListView(DataRow[] _foundRows)
{
lvDepartments.Items.Clear();
ListViewItem depNum = new ListViewItem("NUM", 0);
ListViewItem depName = new ListViewItem("NAME", 0);
foreach (DataRow row in _foundRows)
{
depNum.SubItems.Add(row.Field<string>("NUM"));
depName.SubItems.Add(row.Field<string>("NAME"));
}
lvDepartments.Columns.Add("Number", -2, HorizontalAlignment.Left);
lvDepartments.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvDepartments.Items.AddRange(new ListViewItem[] { depNum, depName });
}
这个
DataRow[]
数组已正确填充
ResizeListView(int _rows)
方法的作用是调整列表的高度
列表视图
正确显示列标题,但其余的只是空行。
我跟着
these instructions
在MSDN上,但我真的找不到我缺少的东西。
任何建议都将不胜感激。
谢谢-