日期:2014-05-20  浏览次数:20933 次

ListView控件问题
运行窗体后,选中ListView中一项,点击下一项按钮焦点到下一项,点击上一项按钮焦点到上一项,如果已是最后一项,最后一项按钮无法使用,如果是第一项则第一项按钮无法使用。点击新增按钮ListView新增一项供添加数据。谢谢!帮忙给出代码

------解决方案--------------------
向上
private void button1_Click(object sender, EventArgs e)
{
int index = listView1.SelectedItems[0].Index;
ListViewItem item = listView1.SelectedItems[0];
listView1.Items.Remove(item);
listView1.Items.Insert(index - 1, item);
item.Selected = true;
if (index - 1 == 0)
{
button1.Enabled = false;
}
}
------解决方案--------------------
向上移
private void button1_Click(object sender, EventArgs e)
{
int index = listView1.SelectedItems[0].Index;
if (index == 0)
{
return;
}
ListViewItem item = listView1.SelectedItems[0];
listView1.Items.Remove(item);
listView1.Items.Insert(index - 1, item);
item.Selected = true;
if (index - 1 == 0)
{
button1.Enabled = false;
}
}
向下移
private void button2_Click(object sender, EventArgs e)
{

int index = listView1.SelectedItems[0].Index;
if (index == listView1.Items.Count - 1)
{
return;
}
ListViewItem item = listView1.SelectedItems[0];
listView1.Items.Remove(item);
listView1.Items.Insert(index + 1, item);
if (index + 1 == listView1.Items.Count)
{
button1.Enabled = false;
}
}
------解决方案--------------------
新增
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0)
{
ListViewItem item = new ListViewItem(textBox1.Text);
listView1.Items.Add(item);
}
}
------解决方案--------------------
for(int i=0;i <this.listview1.SelectedItems.Count;i++) 

System.Windows.Forms.ListViewItem listViewItem = this.listview1.SelectedItems[i]; 
int index = this.listview1.SelectedItems[i].Index - 1; 
if (index < 0) return ; 
this.listview1.Items.Remove(this.listview1.SelectedItems[i]); 
this.listview1.Items.Insert(index, listViewItem); 
listViewItem.Selected = true; 


//下移
for (int i = this.listview1.SelectedItems.Count-1; i > -1; i--) 

System.Windows.Forms.ListViewItem listViewItem = this.listview1.SelectedItems[i]; 
int index = this.listview1.SelectedItems[i].Index + 1; 
if (index > this.listview1.Items.Count -1) return; 
this.listview1.Items.Remove(this.listview1.SelectedItems[i]); 
this.listview1.Items.Insert(index, listViewItem); 
listViewItem.Selected = true;