My first time asking a qustion on this site.
I have a simple windows form created in Visual C# 2008 and I am adding the values from two textboxes to two fields in an access 2010 database. The database is called TestDatabase.accdb and the table is TestTable. Two variables, FirstName & Address are assigned to the textbox.text values of txt.FirstName and txt.Address. It seems to me I am also adding the values to these two variables in statement for adding parameters for the OleDBCommand class:
myCommand.Parameters.Add("@FirstName", OleDbType.VarChar).Value = txtName.Text;
So basically it is working, but I don’t understand the logic becuase it seems as though I wouldn’t need to use
FirstName = txtName.Text;
or
Address = txtAddress.Text;
statements. If I remove the code from the TextChanged events I receive a couple of warnings.
Here is the code:
namespace Test
{
public partial class Form1 : Form
{
private string FirstName;
private string Address;
private void cmdAdd_Click(object sender, EventArgs e)
{
string strSQL = "INSERT INTO TestTable(Name1, Address) VALUES(@FirstName, '@Address')";
// represents an open connection to a data source. Is a class
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\TEMP\\TestDatabase.accdb");
// represents an SQL statement or stored procedure to execute against a data source
//( takes care of passing queries to the database). Is a class.
OleDbCommand myCommand = new OleDbCommand(strSQL, myConnection);
myCommand.Parameters.Add("@FirstName", OleDbType.VarChar).Value = txtName.Text;
myCommand.Parameters.Add("@Address", OleDbType.VarChar).Value = txtAddress.Text;
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Something went wrong");
}
finally
{
myConnection.Close();
}
}
private void txtName_TextChanged(object sender, EventArgs e)
{
//IsNullOrEmpty indicates whether the string is null ot an Empty string
//true if the value parameter is null or an empty string(""); otherwise, false
if (string.IsNullOrEmpty(txtName.Text))
{
//has no value
}
else
{
FirstName = txtName.Text;
}
}
private void txtAddress_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtAddress.Text))
{
//has no value
}
else
{
Address = txtAddress.Text;
}
}
}
}
Welcome to SO, Kevin!
Just to clarify, you aren’t setting the values twice here, per se.
You are setting the value in the code above.
And in the code above you are re-assigning the values to a parameter or, in other words, parameterizing the values. This is a good practice to use and understand as it can help protect you from SQL Injection attacks.