Simple textbox connected with button, SQL - sql

I need to make complicated form which includes textboxes and buttons. But I would like to learn how to do in on simple example. I am connecting to local SQL server with application written in visual basic.
How can I make very simple form, for example with first name and last name and with submit button, which sends those data to database? Here is my code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection
("Server=[...];Initial Catalog=[...]);
}
Everything is fine with connection, but I need to insert data with textboxes and buttons.

Try Like this
private void button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Server=[...];Initial Catalog=[...]");
conn.Open();
string sql = "INSERT INTO User (firstname,lastname)VALUES(#fname,#lname)";
cmd.CommandText = sql;
cmd.Connection = conn;
cmd.Parameters.Add("#fname", SqlDbType.VarChar, 100);
cmd.Parameters["#fname"].Value = TextBox1.Text;
cmd.Parameters.Add("#lname", SqlDbType.VarChar, 100);
cmd.Parameters["#fname"].Value = TextBox2.Text;
cmd.ExecuteNonQuery();
}

Related

ADO.net Performing Multiple queries (ExecuteQuery & ExecuteScalar) and displaying the result in a web form control

Hey wish you all to have a happy holiday,
I am trying to display multiple query results from a SQL database table to a grid view control and a label. I have no problem with the grid view result, but the result from the ExecuteScalar command is not displaying inside my lable control with an ID="myCount". I could not figure out what went wrong with my code. I need your help.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MBSDB"].ConnectionString);
try {
conn.Open();
string query="SELECT * FROM tblBook";
using (SqlCommand mycmd = new SqlCommand(query, conn)) {
myGrid.DataSource = mycmd.ExecuteReader();
myGrid.DataBind();
}
string query2 = "SELECT count(title) FROM tblBook";
using (SqlCommand mycmd2 = new SqlCommand(query2, conn)) {
int count = (int)mycmd2.ExecuteScalar();
myCount.Text = count.ToString();
}
}
catch {
Exception(e);
}
finally { conn.Close(); }
}
Are you sure about there is no error. I think, the error occured and handling in the catch block and you are unaware of it.
You should change it;
(int)mycmd2.ExecuteScalar();
to
Convert.ToInt32(mycmd2.ExecuteScalar());
You can't unboxing an object like this; (int)mycmd2.ExecuteScalar()

Login form in ASP.net does not work

I'm new to ASP.net and currently failing to create a simple functioning login form. After establishing the connection to my database, I wanted the function to check whether a given combination of username and password exists in the database. Due to the fact that I have not created the "member zone" page yet, It's supposed to do nothing if the data is valid and return "Login failed" in the opposite case. For some reason, it doesn't work. I would be glad if someone could help me trace the problem.
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT * FROM users WHERE username='" + UserName.Text +
"' AND password='" + Password.Text + "' ";
SqlCommand cmd = new SqlCommand(query, con);
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
Response.Write("Login failed.");
}
You have SELECT * FROM in the query and you are using ExecuteScalar method to check if anything is returned.
You should use SELECT COUNT(*) FROM to get the number of rows exist in the table for given username and password.
Another thing which is not right in your code is the generation of query. Using parameterized query is the most recommended approach.
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT COUNT(*) FROM users WHERE username=#userName AND password=#password";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#userName", UserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", Password.Text));
con.Open();
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
{
Response.Write("Login failed.");
}
This should resolve your issue.
You forgot to open connection before executing ExecuteScalar()
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT COUNT(*) FROM users WHERE username=#userName AND password=#password";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#userName", UserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", Password.Text));
//Add Below line and test your code.
con.Open();
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
{
Response.Write("Login failed.");
}

How do I print SQL query using MessageBox in C#

I am stuck with this problem since yesterday. I have created a button, which when clicked display the results from a SQL Server table. I thought of using MessageBox to print these results or if there is any other way to print results?
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * FROM Products", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
command.ExecuteNonQuery();
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
I have tried different methods but it never worked.. I am really stuck. If you want more details, let me know. Thanks for the help in advance
Add a datagridview control to show multiple rows and try this code and rename it what you want and replace this YourDataGridVeiwName from the name you set for datagridview control and try below code
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
DataTable dt = new DataTable();
sda.Fill(dt);
YourDataGridVeiwName.DataSource= dt;
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
You need to use the SqlDataReader and iterate over the rows returned, extract what you need from each row, and then display that to the enduser.
I modified your code a bit, to make it safer (using blocks!), and I modified the query to return only the product name (assuming you have that) since you cannot really display a whole row in a message box....
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string productName = reader.GetFieldValue<string>(0);
MessageBox("Product is: " + productName);
}
reader.Close();
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}

Why SQL will only update the text boxes original text? ASP.Net

so the problem I'm having is that on my button click it's supposed to update the database with the values in the text boxes. These are being read in on the page load. Having modified the code a bit to see what's going on, even if the content of the text box is changed, it submits the original text. I can't wrap my head around why. I need it to submit any changes to those text boxes. Any help or guidance appreciated.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
string checkic1 = "SELECT colum1 FROM table1 WHERE ID='1';";
SqlCommand c1Comm = new SqlCommand(checkic1, con);
string ic1 = c1Comm.ExecuteScalar().ToString();
con.Close();
c1TxtBox.Text = ic1;
}
The example above is the same for c2TxtBox and c3TxtBox as well.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection update = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string addUpdate= "UPDATE table1 SET colum1 = #c1, colum2 = #c2, colum3 = #c3 WHERE ID='1';";
SqlCommand comA = new SqlCommand(addUpdate, update);
comA.Parameters.AddWithValue("#c1", c1TxtBox.Text);
comA.Parameters.AddWithValue("#c2", c2TxtBox.Text);
comA.Parameters.AddWithValue("#c3", c3TxtBox.Text);
update.Open();
comA.ExecuteNonQuery();
update.Close();
Response.Redirect("originalPage.aspx");
}
}
The PageLoad function is called everytime you load the page, also when you submit the page by clicking your button. Therefore, the value of the textbox is overwritten before you try to update your database (because PageLoad is called before Button1_Click).
To overcome this, you could add a check to see if you are currently in a post back in your PageLoad method, like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
string checkic1 = "SELECT colum1 FROM table1 WHERE ID='1';";
SqlCommand c1Comm = new SqlCommand(checkic1, con);
string ic1 = c1Comm.ExecuteScalar().ToString();
con.Close();
c1TxtBox.Text = ic1;
}
}

Values not updates after update query

I am developing a project in ASP.NET with c# and SQL Server 2005 as back end. It includes a page profile.aspx which displays the information of a user from database. The session variable is used to keep track of the current logged in user.
The profiles table in the database contains a username column and 10 others columns like dept, address, contact, skills, interests etc etc.
I am displaying all these values on profile.aspx. Another page is edit_profile.aspx which comes up when the edit button on profile.aspx is clicked. Here the data is displayed in textboxes, with older entries already displayed, which can be edited, and click the Update button to confirm.
The update query runs fine, there is no error, but the values are not updates in the database tables. What is the possible reason? Solution?
Thank you
protected void Page_Load(object sender, EventArgs e)
{
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlDataAdapter sda = new SqlDataAdapter("select * from profiles where username='" + Session["currentusername"].ToString()+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "profiles");
txt_name.Text = ds.Tables["profiles"].Rows[0][0].ToString();
txt_deptt.Text = ds.Tables["profiles"].Rows[0][1].ToString();
txt_qualificatns.Text = ds.Tables["profiles"].Rows[0][2].ToString();
txt_add.Text = ds.Tables["profiles"].Rows[0][3].ToString();
txt_contacts.Text = ds.Tables["profiles"].Rows[0][4].ToString();
txt_interests.Text = ds.Tables["profiles"].Rows[0][5].ToString();
txt_awards.Text = ds.Tables["profiles"].Rows[0][6].ToString();
txt_website.Text = ds.Tables["profiles"].Rows[0][7].ToString();
txt_skills.Text = ds.Tables["profiles"].Rows[0][8].ToString();
txt_mstatus.Text = ds.Tables["profiles"].Rows[0][9].ToString();
ds.Reset();
}
protected void Button1_Click(object sender, EventArgs e)
{
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlCommand sda = new SqlCommand("update profiles set department='"+txt_deptt.Text+"',qualifications='"+txt_qualificatns.Text+"', address='"+txt_add.Text+"', contacts='"+txt_contacts.Text+"', interests='"+txt_interests.Text+"', awards='"+txt_awards.Text+"', website='"+txt_website.Text+"', skills='"+txt_skills.Text+"', mstatus='"+txt_mstatus.Text+"' where username='" + Session["currentusername"].ToString() + "'", con);
DataSet ds = new DataSet();
try
{
con.Open();
int temp=sda.ExecuteNonQuery();
con.Close();
if (temp >= 1)
{
lbl_message.ForeColor = System.Drawing.Color.Green;
lbl_message.Text = "Profile Updated Successfully!";
}
else
{
lbl_message.ForeColor = System.Drawing.Color.Red;
lbl_message.Text = "Integer less than 1";
}
}
catch
{
lbl_message.ForeColor = System.Drawing.Color.Red;
lbl_message.Text = "Try Again Later, An Error Occured!";
}
//Response.Redirect("profile.aspx");
}
}
You are overwriting the contents of your textboxes every time the page loads so the user inputted conntet is never written to the database...
Look at the Page.IsPostBack method. Basically, wrap the commands to fill the textboxes with
if (!Page.IsPostBack) {}
To only load the values into the text box the first time the page loads (and so not overwrite the user entered values when you click the button you need to check that the page isn't a post back.
I think maybe a book on basic ASP.Net will help answer many questions you may have early on.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlDataAdapter sda = new SqlDataAdapter("select * from profiles where username='" + Session["currentusername"].ToString()+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "profiles");
txt_name.Text = ds.Tables["profiles"].Rows[0][0].ToString();
txt_deptt.Text = ds.Tables["profiles"].Rows[0][1].ToString();
txt_qualificatns.Text = ds.Tables["profiles"].Rows[0][2].ToString();
txt_add.Text = ds.Tables["profiles"].Rows[0][3].ToString();
txt_contacts.Text = ds.Tables["profiles"].Rows[0][4].ToString();
txt_interests.Text = ds.Tables["profiles"].Rows[0][5].ToString();
txt_awards.Text = ds.Tables["profiles"].Rows[0][6].ToString();
txt_website.Text = ds.Tables["profiles"].Rows[0][7].ToString();
txt_skills.Text = ds.Tables["profiles"].Rows[0][8].ToString();
txt_mstatus.Text = ds.Tables["profiles"].Rows[0][9].ToString();
ds.Reset();
}
}