listview 之编辑

ListView双击产生可编辑输入的TextBox(转)
2009-09-20 19:34
运用鼠标事件point 类 Point mousePos = new Point(0,0);
在ListView的鼠标事件下
         private void listView1_MouseMove( object sender, System.Windows.Forms.MouseEventArgs e)
         {
            
// record mouse position
             mousePos.X = e.X;
             mousePos.Y
= e.Y;
         }
然后对ListView的双击事件处理
       //found clicked item
   ListViewItem item = listView1.GetItemAt(mousePos.X,mousePos.Y); //获取鼠标所点击在哪一列上
存在ListView产生滑块,这样就不能精确获得显示列的X,Y值,为获取滑块滑动的距离,可以使用API来得到
using System.Runtime.InteropServices;          
[DllImport("user32")]
public static extern int GetScrollPos(int hwnd, int nBar) ;

                 // locate text box
                 Rectangle rect = item.GetBounds(ItemBoundsPortion.Entire);
                
int StartX = rect.Left;
                
int ColumnIndex = 0 ;
                
// get ColumnIndex
                //得到滑块的位置
                int pos = GetScrollPos(this.
listView1 .Handle.ToInt32(),0);
                 foreach (ColumnHeader Column in listView1.Columns)
                 {
                    
if (mousePos.X + pos >= StartX + Column.Width)
                     {                                    
                         StartX
+= Column.Width;
                         ColumnIndex
+= 1 ;
                     }

                 }

                
// locate the txtinput and hide it. txtInput为TextBox
                 txtInput.Parent = listView1;
                
// begin edit
                 if (item != null )
                 {
                     rect.X
= StartX;
                     rect.Width
= listView1.Columns[ColumnIndex].Width; //得到长度和ListView的列的长度相同
                     txtInput.Bounds
= rect;
                    
// show textbox
                     txtInput.Text = item.SubItems[ColumnIndex].Text;
                     txtInput.Visible
= true ;
                     txtInput.Focus();
                 }
向ListView加载数据
ListViewItem item;
foreach(DataRow dr in ds.Tables[0].Rows)
{
      item = new ListViewItem(dr[0].ToString());
       item.subItem.add(dr[1].ToString());
     ListView.Item.Add(item);
}

你可能感兴趣的:(ListView)