如何编辑列表视图中的项目和子项目?假设我有一个包含3列和子项的列表视图,
__PRE__
我如何将这样的项目添加到listview中?如果我需要在运行时在触发事件时进行编辑,我将如何编辑让我们说按索引[]的行名称?
Cra*_*gTP 24
如果您正在寻找"就地"编辑ListView内容(特别是详细信息视图模式下ListView的子项),您需要自己实现,或使用第三方控件.
默认情况下,使用"标准"可以达到的最佳效果ListView是将其LabelEdit属性设置为true,以允许用户编辑第一列的文本ListView(假设您要允许自由格式文本编辑).
ListView允许"就地"编辑子项的自定义的一些示例(包括完整源代码)是:
小智 17
我使用隐藏的文本框来编辑所有listview项目/子项目.唯一的问题是文本框在文本框外发生任何事件时都需要消失,列表视图不会触发滚动事件,因此如果滚动列表视图,文本框仍然可见.为了绕过这个问题,我用这个覆盖的列表视图创建了Scroll事件.
这是我的代码,我不断重复使用它,这可能对某人有所帮助:
ListViewItem.ListViewSubItem SelectedLSI;
private void listView2_MouseUp(object sender, MouseEventArgs e)
{
ListViewHitTestInfo i = listView2.HitTest(e.X, e.Y);
SelectedLSI = i.SubItem;
if (SelectedLSI == null)
return;
int border = 0;
switch (listView2.BorderStyle)
{
case BorderStyle.FixedSingle:
border = 1;
break;
case BorderStyle.Fixed3D:
border = 2;
break;
}
int CellWidth = SelectedLSI.Bounds.Width;
int CellHeight = SelectedLSI.Bounds.Height;
int CellLeft = border + listView2.Left + i.SubItem.Bounds.Left;
int CellTop =listView2.Top + i.SubItem.Bounds.Top;
// First Column
if (i.SubItem == i.Item.SubItems[0])
CellWidth = listView2.Columns[0].Width;
TxtEdit.Location = new Point(CellLeft, CellTop);
TxtEdit.Size = new Size(CellWidth, CellHeight);
TxtEdit.Visible = true;
TxtEdit.BringToFront();
TxtEdit.Text = i.SubItem.Text;
TxtEdit.Select();
TxtEdit.SelectAll();
}
private void listView2_MouseDown(object sender, MouseEventArgs e)
{
HideTextEditor();
}
private void listView2_Scroll(object sender, EventArgs e)
{
HideTextEditor();
}
private void TxtEdit_Leave(object sender, EventArgs e)
{
HideTextEditor();
}
private void TxtEdit_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
HideTextEditor();
}
private void HideTextEditor()
{
TxtEdit.Visible = false;
if (SelectedLSI != null)
SelectedLSI.Text = TxtEdit.Text;
SelectedLSI = null;
TxtEdit.Text = "";
}
Run Code Online (Sandbox Code Playgroud)
对不起,没有足够的代表,或者会对CraigTP的答案发表评论.
我从第一个链接 - C#Editable ListView找到了解决方案,非常容易使用.一般的想法是:
SubItem所选择的内容并覆盖一个TextBox带有SubItem文本的文本SubItemTextBox焦点SubItem的文字说的TextBox的时候TextBox失去焦点什么一种解决方法看似简单的操作: - |
单击列表视图中的项目.添加一个按钮,用于编辑所选项目.添加代码
try
{
LSTDEDUCTION.SelectedItems[0].SubItems[1].Text = txtcarName.Text;
LSTDEDUCTION.SelectedItems[0].SubItems[0].Text = txtcarBrand.Text;
LSTDEDUCTION.SelectedItems[0].SubItems[2].Text = txtCarName.Text;
}
catch{}
Run Code Online (Sandbox Code Playgroud)