【发布时间】:2021-11-14 13:45:02
【问题描述】:
有时我想在特定行的项目列中向 ListView 添加文本。
有时想显示一个 ComboBox 供用户选择条目。
我需要创建一个从 ListView 控件派生的类吗?
这是我目前所拥有的:
ListView lv = new ListViewEx();
lv.Size = new Size(300, 300);
this.Controls.Add(lv);
lv.View = View.Details;
lv.FullRowSelect = true;
lv.Scrollable = true;
lv.Columns.Add("Column 1");
lv.Columns.Add("Column 2");
lv.Columns.Add("Column 3");
lv.Columns.Add("Column 4");
string[] testresult = new string[] { "Pass", "Pass", "Pass", "Pass" };
testresult = new string[] { "Pass", "Pass", "Pass", "Pass" };
ListViewItem itm;
itm = new ListViewItem(testresult);
lv.Items.Add(itm);
// need to add a ComboBox in the 4th column of this list view item and a way to get the value selected from it
testresult = new string[] { "Pass", "Pass", "Pass", "Click To Enter Pass/Fail Result" };
itm = new ListViewItem(testresult);
lv.Items.Add(itm);
private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
var lv = sender as ListView;
var subItem = lv.HitTest(lv.PointToClient(MousePosition)).SubItem;
if (subItem != null && e.SubItem == subItem)
{
using (var brush = new SolidBrush(SystemColors.Highlight))
{
e.Graphics.FillRectangle(brush, e.SubItem.Bounds);
}
if (e.SubItem.Text == "Click To Enter Pass/Fail Result")
{
TextRenderer.DrawText(e.Graphics, e.SubItem.Text, e.SubItem.Font,
e.Bounds, SystemColors.HighlightText, flags);
}
else
{
TextRenderer.DrawText(e.Graphics, e.SubItem.Text, e.SubItem.Font,
e.Bounds, SystemColors.HighlightText, flags);
}
}
else
{
e.DrawDefault = true;
}
}
【问题讨论】:
-
DataGridView 可能更适合这个
-
您可以使用类似这样的东西:How to get the selected SubItem index in a Listview and highlight it?,来检测 SubItem 是否为空并在
subItem.Bounds坐标处放置一个 ComboBox(代替或除了突出显示内容之外)。 -- 我同意使用 DataGridView 整体上会更简单。 -
我尝试了 DataGridView,但 ListView 更适合我的应用程序,Jimi 你能告诉我怎么做吗?
-
好的。我能够添加该方法 listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e) 但是当e.SubItem.Text ==“单击以输入通过/失败结果”时,如何更改该方法以在该单元格中添加一个组合框。并且还添加一个处理程序来获取在 ComboBox 中选择的部分的结果。请参阅上面的更新代码。,