我正在listview中工作,我正在尝试在其中添加角色。 我有验证方法,以防止列表视图具有重复的角色。 问题是当我选择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将保持编辑模式,直到其名称被更改或唯一。