William Burke
William Burke

Reputation: 19

How to validate winforms field for uniqueness

I have code that checks for unique values when the user updates an ID field, but I am so new I am wondering if there is a better way.

private void tbPrinterID_Validating(object sender, CancelEventArgs e)
{
    using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.LazerMaintenance_Conn))
    {
        try
        {
            string query = "SELECT COUNT(*) as Count FROM Printers WHERE PrinterID = '" + tbPrinterID.Text + "'";
            SqlDataAdapter da = new SqlDataAdapter(query, conn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if ((Int32)dt.Rows[0]["Count"] > 0)
            {
                MessageBox.Show("There is already a printer with ID = " + tbPrinterID.Text);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error occured! : " + ex);
        }
    }
}

Upvotes: 0

Views: 56

Answers (1)

Alexander Pope
Alexander Pope

Reputation: 1224

Your example is vulnerable to SQL injection, I suggest reading this What are good ways to prevent SQL injection?.

You can make the query a bit more idiomatic:

var sql = "SELECT 1 FROM Printers WHERE PrinterID = @IdToCheck";

using (var command = new SqlCommand(sql, con))
{
    command.Parameters.AddWithValue("@IdToCheck", tbPrinterID.Text);
    con.Open();
    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
         ..........
        }
    }
}

Upvotes: 1

Related Questions