保存文本框中以逗号分隔的唯一值



我有一个要求,在文本框中,我将保存逗号分隔的值,但在保存时,我想检查值是否应该不同。有人能帮我如何实现吗

注意:-当保存另一个已经保存的具有相同值的记录时,会抛出已经存在的异常记录,但对于相同的记录,它保存的是重复的值。在此处输入图像描述

好的,那么一个文本并说一个按钮。此标记:

<asp:TextBox ID="TextBox1" runat="server" Height="20px" Width="255px"></asp:TextBox>
<br />
<asp:Label ID="Label1" runat="server" ForeColor="Red" Text=""></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />

然后我们的代码:

protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "";
if (TextBox1.Text != "")
{
string s = TextBox1.Text.Replace(" ", "");
string[] nItems = s.Split(',');
// make sure no duplications in input eg: ABC,DEF,ABC
List<string> MyCheckList = new List<string>();
foreach (string sCheck in nItems)
{
if (MyCheckList.Contains(sCheck))
{
Label1.Text = "Reapted token not allowed";
return;
}
else
MyCheckList.Add(sCheck);
}
// ok, no tags repeat in user input,
// sort the items, and then check if in database.
MyCheckList.Sort();
s = string.Join(",",MyCheckList);
// check database for this value
string strSQL = "SELECT COUNT(*) FROM Table1 WHERE Twitter_HashTags = @Tags";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("@Tags", SqlDbType.NVarChar).Value = s;
conn.Open();
int? FoundCount = cmdSQL.ExecuteScalar() as int?;
if (FoundCount > 0)
{
Label1.Text = "Those tags already exist in database";
return;
}
else
{
// not in database - add it  (paramter already set)
cmdSQL.CommandText = "INSERT INTO Table1 (Twitter_HashTags) VALUES(@Tags)";
cmdSQL.ExecuteNonQuery();  
}
}
}
// we are good here - update text box with sorted tags, and spaces removed
TextBox1.Text = s;
}
}

最新更新