我编写代码文本框以添加列表框值。我想为重复添加提供显示错误,但这不起作用。有人可以帮忙吗?
protected void btnAdd_Click(object sender, EventArgs e)
{
AddToList();
lstValue.Items.Remove("");
}
private void AddToList()
{
if (lstValue.Items.Count > 0)
{
txtQlt.Text = txtQlt.Text + "," + cmbQualityRef.SelectedItem.ToString();
}
else
{
txtQlt.Text = cmbQualityRef.SelectedItem.ToString();
}
ListItem itm = new ListItem();
itm.Value = cmbQualityRef.SelectedValue;
itm.Text = cmbQualityRef.SelectedItem.ToString();
if (itm != null)
{
lblMsg.Text = "Selected Item Already Exists In The List.";
return;
}
lstValue.Items.Add(itm);
lstValue.Items.Remove("");
}
答案 0 :(得分:1)
您可以使用items.Contains并检查字符串。这是通过分配itm值和降低你的功能。
private void AddToList()
{
if (lstValue.Items.FindByText(cmbQualityRef.SelectedItem.ToString()) == null)
{
if (lstValue.Items.Count > 0)
{
txtQlt.Text = txtQlt.Text + "," + cmbQualityRef.SelectedItem.ToString();
}
else
{
txtQlt.Text = cmbQualityRef.SelectedItem.ToString();
}
ListItem itm = new ListItem();
itm.Value = cmbQualityRef.SelectedValue;
itm.Text = cmbQualityRef.SelectedItem.ToString();
lstValue.Items.Add(itm);
}
else
{
lblMsg.Text = "Selected Item Already Exists In The List.";
}
}
答案 1 :(得分:0)
使用以下代码示例检查列表
private void AddToList()
{
if (lstValue.Items.Count > 0)
{
txtQlt.Text = txtQlt.Text + "," + cmbQualityRef.SelectedItem.ToString();
}
else
{
txtQlt.Text = cmbQualityRef.SelectedItem.ToString();
}
if (lstValue.Items.FindByText(txtQlt.Text.ToString()) != null)
{
//record is present in list and you code for msg
lblMsg.Text = "Selected Item Already Exists In The List.";
return;
}
else
{
ListItem itm = new ListItem();
itm.Value = cmbQualityRef.SelectedValue;
itm.Text = cmbQualityRef.SelectedItem.ToString();
lstValue.Items.Add(itm);
lstValue.Items.Remove("");
}
}
其中lstValue是ListBox的id