C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > listview添加combobox到单元格

C# listview添加combobox到单元格的实现代码

投稿:mdxy-dxy

从别处转来的,自己进行了一些小的修改,还不错,你自己先拖一个ListView1和一个ComboBox1,需要的朋友可以参考下

实现代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    ListViewItem lvi;
    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      comboBox1.Visible = false;
      listView1.Columns.Add("第一列");
      listView1.Columns.Add("第二列");
      listView1.Columns.Add("第三列");
      this.comboBox1.Items.Add("科比");
      this.comboBox1.Items.Add("姚明");
      this.comboBox1.Items.Add("杜兰特");
      this.comboBox1.Items.Add("邓肯");
      ListViewItem item;
      item = new ListViewItem(1.ToString());
      item.SubItems.Add("姚明");
      item.SubItems.Add("科比");
      listView1.Items.Add(item);
      item = new ListViewItem(2.ToString());
      item.SubItems.Add("邓肯");
      item.SubItems.Add("杜兰特");
      listView1.Items.Add(item);

    }

    private void listView1_MouseUp(object sender, MouseEventArgs e)
    {

      lvi = this.listView1.GetItemAt(e.X, e.Y);
      if (lvi != null)
      {
        //获取选中行的Bounds 
        Rectangle Rect = lvi.Bounds;
        int LX = listView1.Columns[0].Width;
        int RX = listView1.Columns[0].Width + listView1.Columns[1].Width;
        // if (e.X > RX || e.X < LX)
        //{
        this.comboBox1.Visible = false;
        Rect.X = listView1.Left + listView1.Columns[0].Width + 2;
        Rect.Y = this.listView1.Top + 2+Rect.Y;
        Rect.Width = listView1.Columns[1].Width + 2;
        this.comboBox1.Bounds = Rect;
        this.comboBox1.Text = lvi.SubItems[1].Text;
        this.comboBox1.Visible = true; 
        this.comboBox1.BringToFront();
        this.comboBox1.Focus();
        //}
        // int intColIndex = lvi.SubItems.IndexOf(lvi.GetSubItemAt(e.X, e.Y));
      }
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
      lvi.SubItems[1].Text = comboBox1.Text;
      // comboBox1.Visible = false;
    }

    private void comboBox1_MouseLeave(object sender, EventArgs e)
    {
      lvi.SubItems[1].Text = comboBox1.Text;
     // comboBox1.Visible = false;
    }
  }
}
您可能感兴趣的文章:
阅读全文