以combobox为例。
假如一行里面只有一个combobox。
//在类中声明一个控件数组 private ComboBox[] cmds = null; //initview中调用dao组件获得显示的对象列表 List<Indicator> plist = idao.queryIndicators(); //根据对象列表个数new一组cmds cmds=new ComboBox[plist.Count]; //在view的SelectedIndexChanged事件中 if (this.listView1.SelectedItems.Count > 0) { //获得选中的行 ListViewItem item = this.listView1.SelectedItems[0]; //获得行号 int index=this.listView1.SelectedIndices[0]; cmds[index] = new ComboBox(); for (int i = 1; i <= 50; i++){ cmds[index].Items.Add(i + ""); cmds[index].SelectedItem = "20"; cmds[index].Bounds = item.SubItems[3].Bounds; listView1.Controls.Add(cmds[index]); cmds[index].Show(); }
}
如果一行有多个combobox呢? 这和一行一个的区别在于,一行两个不仅需要确定选中的是哪行,还要确定哪列。
虽然只差这一点,但是实现确完全不同。
private void indicatorView_MouseMove(object sender, MouseEventArgs e)//获取鼠标位置
{
mousePos.X = e.X;
mousePos.Y = e.Y;
}
private void indicatorView_Click(object sender, EventArgs e) { ListViewItem item = indicatorView.GetItemAt(mousePos.X, mousePos.Y);//根据鼠标当前位置得到item Rectangle rect = item.GetBounds(ItemBoundsPortion.Entire); int StartX = rect.Left; int ColumnIndex = 0; int pos = GetScrollPos(this.indicatorView.Handle.ToInt32(), 0); foreach (ColumnHeader Column in indicatorView.Columns)//选中的哪一列 { if (mousePos.X + pos >= StartX + Column.Width) { StartX += Column.Width; ColumnIndex += 1; } } if (ColumnIndex == this.indicatorView.Columns.Count - 1)//如果选中最后一列 { int index = this.indicatorView.SelectedIndices[0]; indicatorViewComboBox[index] = new ComboBox(); for (int i = 0; i <= 50; i+=10) indicatorViewComboBox[index].Items.Add(i + ""); indicatorViewComboBox[index].SelectedItem = "20"; indicatorViewComboBox[index].Bounds = item.SubItems[ColumnIndex].Bounds; indicatorView.Controls.Add(indicatorViewComboBox[index]); indicatorViewComboBox[index].Show(); } else if (ColumnIndex == this.indicatorView.Columns.Count - 2) { //其他列 } }