【发布时间】:2021-12-24 08:53:41
【问题描述】:
我有一个要求,我将在文本框中保存逗号分隔的值,但在保存时我想检查值应该是不同的。有人可以帮助我如何实现它
注意点:- 当保存另一个已经保存的具有相同值的记录时,会抛出异常记录已经存在,但是对于相同的记录,它正在保存重复值。 enter image description here
【问题讨论】:
-
请分享你的代码你做了什么
我有一个要求,我将在文本框中保存逗号分隔的值,但在保存时我想检查值应该是不同的。有人可以帮助我如何实现它
注意点:- 当保存另一个已经保存的具有相同值的记录时,会抛出异常记录已经存在,但是对于相同的记录,它正在保存重复值。 enter image description here
【问题讨论】:
好的,一个文本然后说一个按钮。这个标记:
<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;
}
}
【讨论】: