I have just finished making a contact application, where basically you input the contacts details and it will save it to a SQL database.
I am very sorry if my code is confusing everyone because I am a big noobie at coding.
Connection String
<add name="connstrng" connectionString="Data Source=DESKTOP-MJ61J7L\SQLEXPRESS;Initial Catalog=Econtact;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"/>
C#
class contactClass
{
//getter and setter properties
//acts as data carrier in our application
public int ContactID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ContactNo { get; set; }
public string Address { get; set; }
public string Gender { get; set; }
static string myconnstrng = ConfigurationManager.ConnectionStrings["connstrng"].ConnectionString;
//selecting data from database
public DataTable Select() {
//Database Connection
SqlConnection conn = new SqlConnection(myconnstrng);
DataTable dt = new DataTable();
try
{
//Writing sql query
string sql = "SELECT * FROM tbl_contact";
//creating cmd using sql and conn
SqlCommand cmd = new SqlCommand(sql, conn);
//creating sql dataAdapter using cmd
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
conn.Open();
adapter.Fill(dt);
} catch(Exception e)
{
} finally
{
conn.Close();
}
return dt;
}
//inserting data into DataBase
public bool Insert (contactClass c)
{
//creating a default return type and setting its value to false
bool isSuccess = false;
//Connect to DataBase
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
string sql = "INSERT INTO tbl_contact (FirstName, LastName, ContactNo, Address, Gender) VALUES (#FirstName, #LastName, #ContactNo, #Address, #Gender) ";
//creating cmd using sql and conn
SqlCommand cmd = new SqlCommand(sql, conn);
//Inserting Parameters into tbl_contact
cmd.Parameters.AddWithValue("#FirstName", c.FirstName);
cmd.Parameters.AddWithValue("#LastName", c.LastName);
cmd.Parameters.AddWithValue("#ContactNo", c.ContactNo);
cmd.Parameters.AddWithValue("#Addresss", c.Address);
cmd.Parameters.AddWithValue("#Gender", c.Gender);
conn.Open();
int row = cmd.ExecuteNonQuery();
//if the query runs successfully then the value of the rows will be != 0 (because the default it 0)
if(row > 0)
{
isSuccess = true;
} else
{
isSuccess = false;
}
} catch(Exception e)
{
} finally
{
conn.Close();
}
return isSuccess;
}
//method to update data in our database from our application
public bool Update(contactClass c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
string sql = "UPDATE tbl_contact SET FirstName=#FirstName, LastName=#LastName, ContactNo=#ContactNo, Address=#Address, Gender=#Gender WHERE ContactID=#ContactID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#FirstName", c.FirstName);
cmd.Parameters.AddWithValue("#LastName", c.LastName);
cmd.Parameters.AddWithValue("#ContactNo", c.ContactNo);
cmd.Parameters.AddWithValue("#Addresss", c.Address);
cmd.Parameters.AddWithValue("#Gender", c.Gender);
//open database connection
conn.Open();
int row = cmd.ExecuteNonQuery();
if (row > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception e)
{
}
finally
{
conn.Close();
}
return isSuccess;
}
//method to delete data from our database
public static bool Delete(contactClass c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
//sql to delete data
string sql = "DELETE FROM tbl_contact WHERE ContactID=#ContactID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#ContactID", c.ContactID);
//open sql connection
conn.Open();
int rows = cmd.ExecuteNonQuery();
//runs the isSuccess variable if statement
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch(Exception e)
{
}
finally
{
//Close sql connection
conn.Close();
}
return isSuccess;
}
}
Add Button
private void btnAdd_Click(object sender, EventArgs e)
{
//Get the value from the input fields
c.FirstName = txtboxFirstName.Text;
c.LastName = txtboxLastName.Text;
c.ContactNo = txtboxPhonenumber.Text;
c.Address = txtboxAddress.Text;
c.Gender = cmbGender.Text;
c.FirstName = txtboxFirstName.Text;
//inserting data into the database using the method we created in the last video
bool success = c.Insert(c);
if (success == true)
{
MessageBox.Show("New contact successfully created.");
}
else
{
MessageBox.Show("Failed to add contact. Try Agian.");
}
}
I do think that it might be due to the connection to my data base....
I Also got this message in my output-
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Idk if this means anything though.
#mjwills Addresss is misspelled (twice). That would explain what you are seeing.
Thanks man, uhgg so obvious. I really appreciate it I would never have found that.
Related
I'm having a trouble with my code.
I'm trying to have the user the ability to submit his email to subscribe to my "notify me" service, I havn't code anything lately so I a bit confused..
I'm trying to Insert, Read, and Update data in my Online SQL Server.. but nothing seems to work! I don't know why I tried everything I know I check a million times it seems good.
Plus if there is any errors my catch should show it to me but even that doesn't work :(
Take a look at this maybe your eyes will see something I don't see.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["notifyCS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
try
{
string checkEmail = "SELECT User_Email FROM tbl_users WHERE User_Email = #User_Email";
string checkSubscription = "SELECT User_Status FROM tbl_users WHERE User_Email = #User_Email";
string submitEmail = "INSERT INTO tbl_users (User_UID, User_Email, User_Status) VALUES (#User_UID, #User_Email, #User_Status)";
string submitEmail2 = "UPDATE tbl_users SET User_UID = #User_UID, User_Status = #User_Status WHERE User_Email = #User_Email";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
SqlDataAdapter emailSDA = new SqlDataAdapter
{
SelectCommand = emailCMD
};
DataSet emailDS = new DataSet();
emailSDA.Fill(emailDS);
//if there is no email registered.
if (emailDS.Tables[0].Rows.Count == 0)
{
SqlCommand registerEmail = new SqlCommand(submitEmail, conn);
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail.ExecuteNonQuery();
registerEmail.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
else if (emailDS.Tables[0].Rows.Count > 0)
{
using (SqlCommand checkSub = new SqlCommand(checkSubscription, conn))
{
checkSub.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
SqlDataReader sdr = checkSub.ExecuteReader();
if (sdr.HasRows)
{
string res = sdr["User_Status"].ToString();
if (res != "subscribed")
{
using (SqlCommand registerEmail2 = new SqlCommand(submitEmail2, conn))
{
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail2.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail2.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail2.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail2.ExecuteNonQuery();
registerEmail2.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
}
else
{
conn.Close();
conn.Dispose();
Response.Redirect("index.aspx");
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
}
}
Try it this way:
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
string checkEmail = "SELECT * FROM tbl_users WHERE User_Email = #User";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
emailCMD.Parameters.Add("#User", SqlDbType.NVarChar).Value = email.Text;
SqlDataAdapter da = new SqlDataAdapter(emailCMD);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
DataTable emailRecs = new DataTable();
emailRecs.Load(emailCMD.ExecuteReader());
DataRow OneRec;
if (emailRecs.Rows.Count == 0)
{
OneRec = emailRecs.NewRow();
emailRecs.Rows.Add(OneRec);
}
else
{
// record exists
OneRec = emailRecs.Rows[0];
}
// modify reocrd
OneRec["User_UID"] = User_UID;
OneRec["User_Email"] = email.Text;
OneRec["User_Status"] = "subscribed";
email.Text = null;
da.Update(emailRecs);
}
}
I'm facing a minor problem and I'll tell you all the details below. If you help me I would be very happy.
I have 3 tables in my database as "tbl_User", "tbl_City", "tbl_Town".
My "tbl_User" table:
userid int [PK],
email nvarchar(50),
password nvarchar(50),
city int,
town int
My "tbl_City" table:
cityno int [PK],
cityname nvarchar(50)
My "tbl_Town" table:
townno int,
townname nvarchar(50),
cityno int
As you can see, "tbl_City" and "tbl_Town" tables are related to each other. This means there are towns connected to every city.
While the user is registering on the site, he must choose city and town. So I can save city and town as number in "tbl_User".
What I want to do is: When the user goes "profile.aspx", I want the city and town name to be seen in DropDownLists selectively. And when user click DropDownListCity; I want all the other cities to appear at the same time. And when user click DropDownListTown; I want showing all towns connected to the selected city.
My code bring the city selected in the "tbl_User" and when I click DropDownListCity I can see all other cities. There is no problem here. But my code doesn't bring the town selectively. I get en error: 'System.NullReferenceException'. I think it's because the city is chosen in DropDownList but program does not see the city selected.
My code is as follows:
Fonksiyon function = new Fonksiyon();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCity();
GetTown();
GetCityAndTownSelectively();
}
}
private void GetCityAndTownSelectively()
{
if (Session["userid"] != null)
{
DataRow dr = function.GetDataRow("SELECT tbl_City.cityno, tbl_City.cityname, tbl_Town.townno, tbl_Town.townname FROM tbl_User LEFT JOIN tbl_City on tbl_City.cityno = tbl_User.city LEFT JOIN tbl_Town on tbl_Town.townno = tbl_User.town WHERE userid=" + Session["userid"].ToString());
if (dr == null)
{
Response.Redirect("default.aspx");
}
else
{
DropDownListCity.ClearSelection();
DropDownListCity.Items.FindByValue(dr[0].ToString()).Selected = true;
DropDownListTown.ClearSelection();
DropDownListTown.Items.FindByValue(dr[2].ToString()).Selected = true;
}
}
else
{
Response.Redirect("default.aspx");
}
}
private void GetCity()
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["aytasarimConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT * FROM tbl_City", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
DropDownListCity.DataSource = reader;
DropDownListCity.DataValueField = "cityno";
DropDownListCity.DataTextField = "cityname";
DropDownListCity.DataBind();
reader.Close();
}
catch
{
string message = "<script>alert('Error!');</script>";
Response.Write(message);
}
}
private void GetTown()
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["aytasarimConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT * FROM tbl_Town WHERE cityno='" + DropDownListCity.SelectedValue + "'", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
DropDownListTown.DataSource = reader;
DropDownListTown.DataValueField = "townno";
DropDownListTown.DataTextField = "townname";
DropDownListTown.DataBind();
reader.Close();
}
catch
{
string message = "<script>alert('Error!');</script>";
Response.Write(mesaj);
}
}
protected void DropDownListCity_SelectedIndexChanged(object sender, EventArgs e)
{
GetTown();
}
Program gives the error in the following line: DrpDwnLstTown.Items.FindByValue(dr[2].ToString()).Selected = true; And I think i guess i found the cause of the error: When I changed my GetTown methods SQL query like this: SELECT * FROM tbl_Town my code brings town selectively but when I click DropDownListTown I see all towns. The problem is I have to only see the town connected to the city.
This is the full code you need.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCity();
if (DropDownListCity.Items != null)
{
GetTown(Convert.ToInt32(DropDownListCity.SelectedValue.ToString()));
}
}
}
private void GetCity()
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["aytasarimConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT * FROM tbl_City order by cityName", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
DropDownListCity.DataSource = reader;
DropDownListCity.DataValueField = "cityno";
DropDownListCity.DataTextField = "cityname";
DropDownListCity.DataBind();
reader.Close();
}
catch
{
string message = "<script>alert('Error!');</script>";
Response.Write(message);
}
}
private void GetTown(Int32 selectedCityNo)
{
if (selectedCityNo == 0)
{
DropDownListTown.Visible = false;
}
else
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["aytasarimConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT * FROM tbl_Town WHERE cityno='" + selectedCityNo.ToString() + "' order by townname", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
DropDownListTown.DataSource = reader;
DropDownListTown.DataValueField = "townno";
DropDownListTown.DataTextField = "townname";
DropDownListTown.DataBind();
reader.Close();
}
catch
{
string message = "<script>alert('Error!');</script>";
Response.Write(message);
}
}
}
protected void DropDownListCity_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlCity = (DropDownList)sender;
string selectedID = ddlCity.ID;
DropDownList ddlSelectedCity = (DropDownList)FindControl(selectedID);
GetTown(Convert.ToInt32(ddlSelectedCity.SelectedValue.ToString()));
}
I am trying to connect to the SQL Server database in C#, and check that the database contains an empty table with 3 columns, but I don't know how to check if it is successful or not..
My code:
protected bool checkDB()
{
string ConnectionString = "Server=[serverName];Database=[databaseName];Trusted_Connection=true";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand com = new SqlCommand("SELECT * FROM tableName", con);
// use the connection here
con.Open();
con.Close();
if (success)
{
return true;
}
else
{
return false;
}
}
protected bool checkDB()
{
var connString = #"Server=myServerName\myInstanceName;Database=myDataBase;Integrated Security=true;";
try
{
using (var con = new SqlConnection(connString))
{
con.Open();
using (var com = new SqlCommand("SELECT * FROM tableName", con))
{
// use your query here...
}
}
return true;
}
catch (Exception)
{
return false;
}
}
Sql database is StudentInfo and Table name is Registration
ID----------Name---------------Email---------------------------PhoneNo
1 Munasunghe amilamunasinghe#yahoo.com 0717069425
2 Liyanarachchi hareshliya6#gmail.com 0756706352
protected void Page_Load(object sender, EventArgs e)
{
string query = "select ID, Name, Email, PhoneNo from Registration";
SqlCommand cmd1 = new SqlCommand(query);
DataTable dt1 = GetData(cmd1);
int rowcount = dt1.Rows.Count;
/* I want to read data in each row step by step and assign to variables*/
}
The function GetData is used to get data from the Database.
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
ID is Primarykey.
Results should be like(Name,Email,Phone No are variables and 1,2,... are ID value)
Name[1]=Munasunghe
Name[2]=Liyanarachchi
Email[1]=amilamunasinghe#yahoo.com
Email[2]=hareshliya6#gmail.com
Phone No[1]=0717069425
Phone No[2]=0756706352
I would say you firstly create a new class for storing your data (like StudentInfo)
public class StudentInfo
{
public StudentInfo(int ID, string Name, string Email, string PhoneNo)
{
this.ID = ID;
this.Name = Name;
this.Email = Email;
this.PhoneNo = PhoneNo;
}
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNo { get; set; }
}
Then use this function that return's a List of StudentInfo class
public List<StudentInfo> GetData()
{
List<StudentInfo> data = new List<StudentInfo>();
SqlConnection con = new SqlConnection("Your connection string");
SqlCommand command = new SqlCommand("SELECT * FROM [Registration]", con);
con.Open();
SqlDataReader sdr = command.ExecuteReader();
while(sdr.Read())
{
data.Add((int)sdr["ID"], (string)sdr["Name"], (string)sdr["Email"], (string)sdr["PhoneNo"]);
}
con.Close();
return data;
}
Then you use it like this:
List<StudentInfo> info = GetData();
foreach(StudentInfo si in info)
{
Response.Write("<h3>ID is " + si.ID + "</h3><p>StudentName is " + si.Name + "</p>");
}
To update the values do this:
public void SetValue(int StudentID, String NewName, String NewEmail, String NewPhone)
{
SqlConnection con = new SqlConnection("Your connection string");
SqlCommand command = new SqlCommand("UPDATE [Registration] SET [Name]='" + NewName + "', [Email]='" + NewEmail + "', [PhoneNo]='" + NewPhone + "' WHERE [ID]=" + StudentID + "", con);
con.Open();
command.ExecuteNonQuery();
con.close();
}
And I would suggest you to read some articles about sql
i have registration page and i want to check that username is already exist in database or not in 3 tier architecture.
MyRegistration.cs:
public static int checkusername(string user_txt)
{
int id2 = 0;
string selectstr = "select * from xyz where UserName = '" + user_txt + " ' ";
id2 = DataAccessLayer.ExecuteReader(selectstr);
return id2;
}
and the code behind onclick event of textbox:
protected void txt_username_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txt_username.Text))
{
int id = xyz.checkusername(txt_username.Text.Trim());
if (id > 0)
{
lblStatus.Text = "UserName Already Taken";
}
else
{
lblStatus.Text = "UserName Available";
}
}
}
DataAccessLayer:
public static int ExecuteReader(string Query)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = Query;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
id++;
}
cmd = null;
reader.Close();
con.Close();
return id;
}
I have edited some of your codes try like below... it will help you...
Text change Event :
protected void txt_username_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txt_username.Text))
{
if (xyz.checkusername(txt_username.Text.Trim()))
{
lblStatus.Text = "UserName Already Taken";
}
else
{
lblStatus.Text = "UserName Available";
}
}
}
Check Username :
public bool CheckUsername(string user_txt)
{
bool Result;
Result = DataAccessLayer.ExecuteReader(user_txt);
return Result;
}
Excute Reader :
public bool ExecuteReader(string user_txt)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
SqlCommand cmd = new SqlCommand("select * from xyz where UserName = #UserID", con);
SqlParameter param = new SqlParameter();
param.ParameterName = "#UserID";
param.Value = user_txt;
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
return true;
else
return false;
}
Usually if the "select query" doesn't find a userName with the parameter user_txt you'll id2 will be end up with the value -1. So the appropriate code would be:
if (id ==-1)
{
lblStatus.Text = "UserName Available";
}
if (id>0)
{
lblStatus.Text = "UserName Already Taken";
}
By the way, your code is highly insecure and your database can be easily attacked using SQL Injection I'd recommend you to understand this issue and add parameters to the query to prevent it. C# has its ways to implement this. Don't try to fix the access to the database, just start from scrath keeping in mind SQL Injection.
As others have mentioned, this approach has potentially serious security issues.
However, your problem may lie here user_txt + " ' ". The spaces around the second ', specifically the one before it may lead to the usernames not matching as expected.