Using Visual Studio 2017, I'm trying to build a Windows Forms application that asks a user for specific value from a SQL Server Express database (footballteam
).
User enters a value (@jnumber
) in a text box (textBox1.Text
) which corresponds to the "LIKE" for "JERSEYNUMBER".
Then, the query (commandText) is to be executed after clicking on button (button1_Click
)
Results should display a DataGridView
.
Build results were: "Build: 0 succeeded, 0 failed, 1 up-to-date, 0 skipped".
However, when running the application, user enters a number value for @jnumber
in textBox.Text
, then clicks on button (button1_Click
), but dataGridView1
remains empty; no results.
Goal is also to avoid SQL injection. Appreciate your help.
Code is here:
// directives
using System;
using System.Data
using System.Windows.Forms;
using System.Data.SqlClient;
namespace displaydmlquery
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// variable sql query
var commandText = "SELECT * FROM JERSEY WHERE JERSEYNUMBER LIKE '%' + @jnumber+ '%' ORDER BY ASSIGNMENT_DATE";
// variable connection string
var connectionString = "Server=hostname\\SQLEXPRESS;Database=footballteam;User Id=userid;Password=password";
// Create a connection instance
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create a SqlCommand instance
SqlCommand command = new SqlCommand(commandText, connection);
// Add the parameter to used in the text box input
command.Parameters.Add("@jnumber", SqlDbType.NVarChar, 20).Value = textBox1.Text;
// Execute query
try
{
// open connection
connection.Open();
// create a SqlDataAdapter to execute query
var dataAdapter = new SqlDataAdapter(commandText, connectionString);
// Create command builder
var commandBuilder = new SqlCommandBuilder(dataAdapter);
// Execute query reader
command.ExecuteReader();
// create a data table to hold query
DataTable dtRecord = new DataTable();
// fill in data tbale
sqlDataAdap.Fill(dtRecord);
// Display results in DataGridView
dataGridView1.DataSource = dtRecord;
}
catch
{
// Handle exception, future code
}
finally
{
connection.Close();
}
}
}
}
}