I'm trying to write a pretty straight forward program that pulls data from my SQL Server database. And outputs the correct state and city in they're respective labels from a valid zip code entered in a textbox.
Here's some code I was messing around with. It obviously doesn't work I was just trying out.
I was able to populate a combobox with all of the states associated with a zip/city, but that's it.
// Connection string.
String cnStr;
SqlConnection cn = new SqlConnection();
cnStr = "Data Source=000.00.000.00;Initial Catalog= ;User ID= ;Password= ";
// Assign Connection string to the connection object
cn.ConnectionString = cnStr;
// Open the connection to the SQL Server
cn.Open();
// This statement creates the command object and passes in the SQL statement
// then associates the command to the cn connection object
SqlCommand cmd = new SqlCommand("select distinct state, city from tblZipcodes order by state", cn);
// Open a DataReader
SqlDataReader rdrZip = cmd.ExecuteReader();
cn.Close();
The validation of a zipcode entered in a textbox and have the resulting state and city outputted to their respective labels, from SQL Server.
Always use parameters, never ever build a sql query without parameters, because it leaves your application wide open for sql injection
.
You should use a where clause like this
var sql = "select distinct state, city from tblZipcodes where zipcode = @ZipCode";
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@ZipCode", SqlDbType.VarChar) { Value = myZipCode.Text });
SqlDataReader rdrZip = cmd.ExecuteReader();
}
Use SqlDbType.NVarChar
in case your columntype is NVarChar
in stead of VarChar
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.