我为下拉列表选择值编写代码添加列表框和文本字段,我可以删除列表框值但不能删除文本字段值,请如何编写代码删除文本字段的相同添加值和列表框
我添加下拉列表值AA,其显示列表框和文本框,但单击删除按钮始终删除所选列表框项但不删除文本框值
<div class="col-sm-3">
<asp:TextBox ID="txtQlt" runat="server" CssClass="form-control" Width="348px" OnTextChanged="txtQlt_TextChanged" ReadOnly="true"></asp:TextBox>
</div><div class="col-md-1" style="margin-left:115px;">
<asp:Label ID="Label4" runat="server" ForeColor="Red" Text="*" ></asp:Label>
</div>
</div>
<br />
<div class="row">
<div class="col-sm-2">
<asp:Label ID="Label6" runat="server" Text="Quality reference" Font-Bold="True" Font-Names="arial, helvetica, sans-serif" Font-Size="13px"></asp:Label>
</div>
<div class="col-sm-3">
<asp:DropDownList ID ="cmbQualityRef" runat ="server" CssClass="form-control" Width="250px" >
</asp:DropDownList>
<asp:ListBox ID="lstValue" runat="server" CssClass="content" Rows="5" ValidationGroup="save"
Width="250" ></asp:ListBox>
</div>
<asp:ImageButton ID="btnAdd" runat="server" CssClass="button" Text="Add" ValidationGroup="add"
OnClick="btnAdd_Click" ImageUrl="~/img/Add.png"/>
<asp:ImageButton ID="btnImageRemove" runat="server" OnClick="btnImageRemove_Click"
ImageUrl="~/img/Remove.png" />
<div class="col-md-1" style="margin-left:16px;">
<asp:Label ID="Label7" runat="server" ForeColor="Red" Text="*" ></asp:Label>
</div>
</div>
protected void btnAdd_Click(object sender, EventArgs e)
{
AddToList();
lstValue.Items.Remove("");
}
--------------------------------------------
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();
lblMsg.Text = "";
lstValue.Items.Add(itm);
}
else
{
lblMsg.Text = "Selected Item Already Exists In The List.";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
protected void btnImageRemove_Click(object sender, ImageClickEventArgs e)
{
try
{
if (lstValue.SelectedItem != null)
{
lstValue.Items.Remove(lstValue.SelectedItem);
txtQlt.Text = txtQlt.Text.Replace(lstValue.SelectedItem.ToString(), "").Trim();
}
}
catch (Exception)
{
}
}
答案 0 :(得分:2)
您应该在替换字符串后从列表中删除项目,否则它无法从列表中找到该项目。 您的代码如下:
protected void btnRemove_Click(object sender, EventArgs e)
{
try
{
if (lst.SelectedItem != null)
{
txt.Text = txt.Text.Replace(lst.SelectedItem.ToString(), "").Trim();
lst.Items.Remove(lst.SelectedItem);
}
}
catch (Exception)
{
}
}