原文:C# 双击ListView出现编辑框可编辑,回车确认
//获取鼠标点击的项------API
[DllImport("user32")]
public static extern int GetScrollPos(int hwnd, int nBar);
private TextBox txtInput;
//获取点击项的位置
private void lViewPersonWork_MouseDoubleClick(object sender, MouseEventArgs e)
{
try
{
ListViewItem item = this.lViewPersonWork.GetItemAt(e.X, e.Y);
//找到文本框
Rectangle rect = item.GetBounds(ItemBoundsPortion.Entire);
int StartX = rect.Left; //获取文本框位置的X坐标
int ColumnIndex = 0; //文本框的索引
//获取列的索引
//得到滑块的位置
int pos = GetScrollPos(this.lViewPersonWork.Handle.ToInt32(), 0);
foreach (ColumnHeader Column in lViewPersonWork.Columns)
{
if (e.X + pos >= StartX + Column.Width)
{
StartX += Column.Width;
ColumnIndex += 1;
}
}
if (ColumnIndex < this.lViewPersonWork.Columns.Count - 1)
{
return;
}
this.txtInput = new TextBox();
//locate the txtinput and hide it. txtInput为TextBox
this.txtInput.Parent = this.lViewPersonWork;
//begin edit
if (item != null)
{
rect.X = StartX;
rect.Width = this.lViewPersonWork.Columns[ColumnIndex].Width; //得到长度和ListView的列的长度相同
this.txtInput.Bounds = rect;
this.txtInput.Multiline = true;
//显示文本框
this.txtInput.Text = item.SubItems[ColumnIndex].Text;
this.txtInput.Tag = item.SubItems[ColumnIndex];
this.txtInput.KeyPress += new KeyPressEventHandler(txtInput_KeyPress);
this.txtInput.Focus();
}
}
catch (Exception ex)
{
}
}
//回车保存内容
private void txtInput_KeyPress(object sender, KeyPressEventArgs e)
{
try
{
if ((int)e.KeyChar == 13)
{
if (this.txtInput != null)
{
ListViewItem.ListViewSubItem lvst = (ListViewItem.ListViewSubItem)this.txtInput.Tag;
lvst.Text = this.txtInput.Text;
this.txtInput.Dispose();
}
}
}
catch (Exception ex)
{
}
}
//释放文本框内容
private void lViewPersonWork_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (this.txtInput != null)
{
if (this.txtInput.Text.Length > 0)
{
ListViewItem.ListViewSubItem lvst = (ListViewItem.ListViewSubItem)this.txtInput.Tag;
lvst.Text = this.txtInput.Text;
}
this.txtInput.Dispose();
}
}
catch (Exception ex)
{
}
}