[英]Check if record already exists within the database
我有一个程序允许用户输入电影和有关该电影的详细信息并将它们存储在数据库中。 我的数据库显示在我的 C# 程序中,用户可以 select 行之一,该行中的信息将放入它对应的文本框中,例如标题将 Z34D1F91FB2E514B8576FAB1A7A 中的标题文本框和. 我想要做的是阻止用户点击提交按钮并将相同的记录放入数据库中。
任何帮助,将不胜感激
提交按钮:
private void btnSubmit_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtTitle.Text) || string.IsNullOrWhiteSpace(txtRunTime.Text))
{
MessageBox.Show("Fill in all the required fields");
}
else
{
if (lstStatus.SelectedIndex == 0)
{
Status = "Watched";
}
else
{
Status = "Not Watched";
}
if (lstType.SelectedIndex == 0)
{
Type = "Movie";
}
else
{
Type = "TV Show";
}
con.Open();
SqlCommand cmd = new SqlCommand("insert into dbo.Movies(Title, Genre, RunTime, Type, Status) values('"+txtTitle.Text+"','"+txtGenre.Text+"','"+txtRunTime.Text+"','"+Type+"','"+Status+"')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data transferred into the database!");
con.Close();
txtTitle.Text = "";
txtRunTime.Text = ""; /
}
}
选择行时的代码:
private void DataGridMovies_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if(DataGridMovies.CurrentRow.Index == DataGridMovies.Rows.Count - 1)
{
MessageBox.Show("Empty row selected"); // Display a message to the user
}
else
{
ID = Convert.ToInt32(DataGridMovies.Rows[e.RowIndex].Cells[0].Value.ToString());
txtTitle.Text = DataGridMovies.Rows[e.RowIndex].Cells[1].Value.ToString();
txtGenre.Text = DataGridMovies.Rows[e.RowIndex].Cells[2].Value.ToString();
txtRunTime.Text = DataGridMovies.Rows[e.RowIndex].Cells[3].Value.ToString();
if (DataGridMovies.Rows[e.RowIndex].Cells[4].Value.ToString() == "Movie")
{
lstType.SelectedIndex = 0;
}
else
{
lstType.SelectedIndex = 1;
}// End of IF ELSE Statement
if (DataGridMovies.Rows[e.RowIndex].Cells[5].Value.ToString() == "Watched")
{
lstStatus.SelectedIndex = 0;
}
else
{
lstStatus.SelectedIndex = 1;
}// End of IF ELSE Statement
}//End of IF statement
您需要使用 sql 参数,否则您的 sql 数据库可能会被黑客入侵。
你可以在这里阅读: https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.8 cmd.Parameters.AddWith(name, value)
确定记录是否存在。 如果没有,您将使用插入添加它。 如果不是,则改为更新记录。
根据您可以使用的处理能力,您可能还会考虑自动完成。 这可以隐藏他们只是在更新您已经“找到”的记录的事实。 https://www.grapecity.com/blogs/dynamic-autocomplete-c1textbox
后端的元标记和算法有时会处理重复条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.