我正在尝试在其中添加角色的列表视图中工作。我有防止列表视图具有重复角色的验证方法。问题是当我选择 listView 的另一个列表项时它会抛出两次相同的消息,而当我选择列表视图的滚动条时它会抛出三次相同的消息。我认为以错误的方式使用 listView.BeginEdit()。请 !帮我解决这个问题
代码 :
private void AddDefaultRoles()
{
ListViewItem lvi = new ListViewItem("Reader");
listViewRoles.Items.Add(lvi);
lvi = new ListViewItem("Writer");
listViewRoles.Items.Add(lvi);
lvi = new ListViewItem("Administrator");
listViewRoles.Items.Add(lvi);
lvi = new ListViewItem("Delete");
listViewRoles.Items.Add(lvi);
lvi = new ListViewItem("Admin");
listViewRoles.Items.Add(lvi);
lvi = new ListViewItem("Contributor");
listViewRoles.Items.Add(lvi);
lvi = new ListViewItem("Designer");
listViewRoles.Items.Add(lvi);
}
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
textBox1.Text = "New Role";
ListViewItem lvi = new ListViewItem(textBox1.Text);
listViewRoles.Items.Add(lvi);
lvi.Selected = true;
lvi.BeginEdit();
}
private void listViewRoles_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
ListViewItem lvi = listViewRoles.Items[e.Item];
string newName = e.Label;
if (newName == null)
newName = lvi.Text;
if (!ValidateRoleName(newName, e.Item))
{
lvi.BeginEdit();
return;
}
}
private void listViewRoles_BeforeLabelEdit(object sender, LabelEditEventArgs e)
{
}
private bool ValidateRoleName(string name, int itemIndex)
{
const bool validName = true;
if ((string.IsNullOrEmpty(name.Trim()))) //empty name
{
MessageBox.Show(this, "empty role name", "Rename failed");
return !validName;
}
if (NameExists(name, itemIndex)) //name already exists
{
MessageBox.Show(this, "already exists", "Rename failed");
return !validName;
}
return validName;
}
private bool NameExists(string newName, int itemIndex)
{
const bool nameExists = true;
for (int i = 0; i < listViewRoles.Items.Count; ++i)
{
if (itemIndex == i)
continue;
if (string.Compare(listViewRoles.Items[i].Text.TrimEnd(), newName.TrimEnd(), true) == 0)
{
return nameExists;
}
}
return !nameExists;
}
编辑(来自错位的答案):
private void listViewRoles_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
ListViewItem lvi = listViewRoles.Items[e.Item];
string newName = e.Label;
if (newName == null)
newName = lvi.Text;
if (_checkRoleName)
{
if (!ValidateRoleName(newName, e.Item))
{
_checkRoleName = false;
lvi.BeginEdit();
return;
}
}
else
{
_checkRoleName = true;
lvi.BeginEdit();
}
}
this.listViewRoles.AfterLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this.listViewRoles_AfterLabelEdit);
this.listViewRoles.BeforeLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this.listViewRoles_BeforeLabelEdit);
当我尝试上面的代码时,它会在我更改所选索引时显示一次消息框,但当我单击滚动条时,它会调用 AfterLabelEdit 事件,因此消息会调用两次。我需要一个适当的解决方案,如果添加的 listviewitem 已经存在于 listview 中,则添加的 listViewItem 会在编辑模式下持续存在,直到其名称更改或唯一。