I have values from controls txtUser and txtAppNum on a page webform1.aspx. I am bringing those values to a page, Login.aspx. The code from Login.aspx is below. In the login.aspx page, I want to take the values from the controls txtUserand txtAppNum in webform1.aspx page, I want to check the values against a database, if the values are in the database, I want the page to redirect back to webform1.aspx.
My questions is, when I run the code, only Page_Load but not CheckRecord. Basically when I run the page, I can see the values carried over from the webform1.aspx page to login.aspx, but then that's it, nothing else happens.
What am I doing wrong? Any thoughts, I would greatly appreciate it, I have been stuck on this for a few days. Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient; //to communicate with the Server database
using System.Configuration;
using System.Data; //to use DataSet or DataTable
using System.Text; //for StringBuilder
namespace BLAA_3
{
public partial class login : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs e)
{
Page PreviousPage = Page.PreviousPage;
if (PreviousPage != null)
{
lblUserLogin.Text = ((TextBox)PreviousPage.FindControl("txtUser")).Text;
lblAppLogin.Text = ((TextBox)PreviousPage.FindControl("txtAppNum")).Text;
}
{
string _connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
}
}
public void CheckRecord(object sender, EventArgs e)
{
//get the connection
using (SqlConnection conn = new SqlConnection(#"Data Source=ServerInfo"))
{
//write the sql statement to execute
string sql = "select username FROM BLAA_users WHERE username = #username";
//instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
//attatch the parameter to pass, if no parameter is in the sql no need to attatch
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#username", SqlDbType.VarChar, 50);
prms[0].Value = lblUserLogin.Text.Trim();
cmd.Parameters.AddRange(prms);
conn.Open();
object obj = cmd.ExecuteScalar();
conn.Close();
if (obj != null)
{
Response.Redirect("~/WebForm1.aspx");
}
else
Response.Redirect("http://www.google.com");
}
}
}
}
}
Is CheckRecord an event handler? If not, you don't need the sender and eventArgs in your signature for CheckRecord it can be public void CheckRecord().
It's not being called because your load event isn't calling it. So, inside your Page_Load function.
public void Page_Load(object sender, EventArgs e)
{
Page PreviousPage = Page.PreviousPage;
if (PreviousPage != null)
{
lblUserLogin.Text = ((TextBox)PreviousPage.FindControl("txtUser")).Text;
lblAppLogin.Text = ((TextBox)PreviousPage.FindControl("txtAppNum")).Text;
}
{
string _connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
}
CheckRecord();
}
public void CheckRecord()
{
//get the connection
using (SqlConnection conn = new SqlConnection(#"Data Source=ServerInfo"))
{
//write the sql statement to execute
string sql = "select username FROM BLAA_users WHERE username = #username";
//instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
//attatch the parameter to pass, if no parameter is in the sql no need to attatch
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#username", SqlDbType.VarChar, 50);
prms[0].Value = lblUserLogin.Text.Trim();
cmd.Parameters.AddRange(prms);
conn.Open();
object obj = cmd.ExecuteScalar();
conn.Close();
if (obj != null)
{
Response.Redirect("~/WebForm1.aspx");
}
else
Response.Redirect("http://www.google.com");
}
}
}
Related
When trying to edit the datagridview, an error appears "The CommandText property has not been properly initialized.". I read that some other stored procedure is needed, which as input parameters it takes the first name, last name and patronymic and phone number of the user and returns his id, if so, how to implement it on mysql link to the source: https://metanit.com/sharp/adonet/2.11.php , https://metanit.com/sharp/adonet/3.5.php
Program code:
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SD = System.Data;
namespace DBredaction
{
public partial class Form1 : Form
{
DataSet ds;
MySqlDataAdapter adapter;
MySqlCommandBuilder commandBuilder;
string connectionString = "Server=localhost;Database=catalog;Uid=root;pwd=;charset=utf8;";
string sql = "SELECT * FROM employee";
public Form1()
{
InitializeComponent();
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.AllowUserToAddRows = false;
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
adapter = new MySqlDataAdapter(sql, connection);
ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
// делаем недоступным столбец id для изменения
dataGridView1.Columns["Id"].ReadOnly = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
//public MySqlConnection mycon;
//public MySqlCommand mycom;
//public string connect = "Server=localhost;Database=catalog;Uid=root;pwd=;charset=utf8;";
//public SD.DataSet ds;
//public MySqlCommand mycon2;otchestvo
private void button1_Click(object sender, EventArgs e)
{
try {
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
adapter = new MySqlDataAdapter(sql, connection);
commandBuilder = new MySqlCommandBuilder(adapter);
adapter.InsertCommand = new MySqlCommand("", connection);
adapter.InsertCommand.CommandType = CommandType.StoredProcedure;
adapter.InsertCommand.Parameters.Add(new MySqlParameter("#imia", MySqlDbType.VarChar, 50, "Имя"));
adapter.InsertCommand.Parameters.Add(new MySqlParameter("#familia", MySqlDbType.VarChar, 50, "Фамилия"));
adapter.InsertCommand.Parameters.Add(new MySqlParameter("#otchestvo", MySqlDbType.VarChar, 50, "Отчество"));
adapter.InsertCommand.Parameters.Add(new MySqlParameter("#telephon", MySqlDbType.VarChar, 11, "Телефон"));
MySqlParameter parameter = adapter.InsertCommand.Parameters.Add("#id", MySqlDbType.Int16, 0, "Id");
parameter.Direction = ParameterDirection.Output;
adapter.Update(ds);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button4_Click(object sender, EventArgs e)
{
try
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MessageBox.Show("DB CONNECT");
connection.Close();
}
}
catch
{
MessageBox.Show("Connection lost");
}
}
private void button3_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
dataGridView1.Rows.Remove(row);
}
}
private void button5_Click(object sender, EventArgs e)
{
DataRow row = ds.Tables[0].NewRow();
ds.Tables[0].Rows.Add(row);
}
}
}
It doesn't work quite like that; if you're assigning a command builder to an adapter you don't then also set the XxxCommand DML properties yourself; the command builder does that from looking at the SelectCommand, working out the table schema and writing the queries.
I'd have the adapter at class level in a dedicated repository class, where the select, connstr and command builder are set:
//in the constructor of the repo class
_myDataAdapter = new MySqlDataAdapter("SELECT here", "connstr here");
_commandBuilder = new MySqlCommandBuilder(_myDataAdapter);
the fill code runs:
//in a GetData method of the repo class
DatTable dt = new DataTable();
_myDataAdapter.Fill(dt);
return dt;
and the relevant I/U/D commands can be triggered:
//in a SaveChanges(DataTable) method of the repo class
_myDataAdapter.Update(dt);
See https://www.devart.com/dotconnect/mysql/docs/Devart.Data.MySql~Devart.Data.MySql.MySqlCommandBuilder.html for more background info on the CB; their example code is based on a complete programmatic "fill, change, save" workflow so it's all in one method, but your workflow is essentially interrupted by the user needing to do the changes in the grid, hence breaking it up.
If you want to do it in one method, you can make your adapter, make your command builder and then set the I/U/D commands on the adapter by calling the relevant GetXxx on the command builder
Note that the command builder doesn't use stored procedures; that thing you've read about needing to make a stored procedure to update/insert data isn't the only way to save data to a db, and if you have created a sproc and are hoping to use it, forget a command builder; you'll have to do the command setup yourself
i am encountering an error when trying to set up an insert command into my database, it appears to be with the connection string. I am extremely new to all this and am trying to get the correct code in order to upload into my database and assume that the syntax i am using may be wrong and the cause of the error.
Here is the code a little bit clearer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace ComputingProjectwh.TestPages._1._Further_Mechanics
{
public partial class Moments_and_Energy_Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
if (!this.IsValid)
return;
int score = 0;
List<RadioButtonList> list = new List<RadioButtonList>() { RadioButtonList1, RadioButtonList2, RadioButtonList3, RadioButtonList4, RadioButtonList5, RadioButtonList6, RadioButtonList7, RadioButtonList8, RadioButtonList9, RadioButtonList10 };
foreach (var element in list)
{
if (element.SelectedValue == "Correct")
{
score++;
}
}
Response.Write("you scored: " + score);
Button1.Visible = false;
if (score != 0);
{
SqlConnection sqlConnection1 = new SqlConnection (#"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ComputingProjectwh-20170404101246.mdf;InitialCatalog=aspnet-ComputingProjectwh-20170404101246;IntegratedSecurity=True");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT AspNetUserTestScores (Id, MomentAndEnergyTestScore) VALUES (Id, score)";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
}
}
I am really not sure what the problem is and cant seem to find an answer on the internet. Any help would be greatly appreciated.
When connecting to MSSQL, there is no initialcatalog, You are using a wrong connection string.
This is the correct syntax:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Or in your case, for trusted connection:
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
With your data:
SqlConnection sqlConnection1 = new SqlConnection("Server=LocalDb;Database=aspnet-ComputingProjectwh-20170404101246.mdf;Trusted_Connection=True;");
InitialCatalog is two separate words initial catalog.
I have a Website with 3 signup pages.
every page contains information, and all 3 pages are part of the signup process.
I know that INSERT command is used to create new rows. But in the UPDATE command, I must mention WHERE clause.
So, my question is, how can I UPDATE the same row I updated in the past pages.
I am using Visual Studio Community 2015.
Any help will be appreciated.
First page code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Sign_Up_SignUpMain_1_ : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnNext_Click(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;";
str += "AttachDbFilename=|DataDirectory|Database.mdf;";
str += "Integrated Security= True";
string email, userName;
//Page
if (Page.IsValid == true)
{
email = txtEmail.Text;
userName = txtUserName.Text;
SqlConnection c = new SqlConnection(str);
SqlCommand sqlCommand = new SqlCommand("INSERT INTO [Table] (Email, UserName) VALUES (#email, #userName);", c);
sqlCommand.Connection = c;
sqlCommand.Parameters.AddWithValue("#email", email);
sqlCommand.Parameters.AddWithValue("#userName", userName);
c.Open();
sqlCommand.ExecuteNonQuery();
c.Close();
Response.Redirect("SignUp(2).aspx", true);
}
//Email
if (rfvEmail.IsValid == false || revEmail.IsValid == false)
{ txtEmail.CssClass = "txtError"; }
else
{ txtEmail.CssClass = "Text"; }
//User Name
if (rfvUserName.IsValid == false || revUserName.IsValid == false)
{ txtUserName.CssClass = "txtError"; }
else
{ txtUserName.CssClass = "Text"; }
}
}
Second page code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Sign_Up_SignUp_2_ : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnNext_Click(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;";
str += "AttachDbFilename=|DataDirectory|Database.mdf;";
str += "Integrated Security= True";
string password;
//Page
if (Page.IsValid == true)
{
password = txtPass.Text;
SqlConnection c = new SqlConnection(str);
SqlCommand sqlCommand = new SqlCommand("INSERT INTO [Table] (Email, UserName) VALUES (#email, #userName);", c);
Response.Redirect("SignUp(3).aspx", true);
}
//Password
if (revPass.IsValid == false || rfvPass.IsValid == false)
{ txtPass.CssClass = "txtError"; }
else
{ txtPass.CssClass = "Text"; }
//Confirm Password
if (rfvConPass.IsValid == false)
{ txtConPass.CssClass = "txtError"; }
else
{ txtConPass.CssClass = "Text"; }
//Compare Passwords
if (cvPasswords.IsValid == false)
{
txtPass.CssClass = "txtError";
txtConPass.CssClass = "txtError";
txtPass.Text = "";
txtConPass.Text = "";
}
else
{
txtPass.CssClass = "Text";
txtConPass.CssClass = "Text";
}
}
}
Ok I see your issue, you aren't passing the values that have already been inserted between pages. You can use the Session State to pass objects between parameters
On your current page, before redirecting to the next page, set all the information you want to retain in the session state:
Session["email"] = theirEmailAddress;
Session["username"] = theirUserName;
After storing the information you need in the session redirect to the next page and store the information on this page into the session as well.
Then finally on the last page you can access all of the session data and do a single SQL insert command. To access the session items you just do this:
string email = (string)(Session["email"]);
Another ASP.NET C# noobie question...
The following codebehind populates a dropdown list from a database. There are three columns in the table (ID, ItemType & BinType). I need to be able to return the correct BinType for the row selected by the user:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
// Global variable for SqlConnection
OleDbConnection con = new OleDbConnection();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// specifying sqlconnection string
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_GRPAS_dev"].ConnectionString;
{
// Select rows from database where the ItemType field isn't empty. Sort them alphabetically by ItemType
using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM NF_WhatWasteWhere WHERE ItemType <>'' Order By ItemType"))
{
//Open the connection and populate the dropdown list with ID and Itemtype
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
ItemType1.DataSource = cmd.ExecuteReader();
ItemType1.DataTextField = "ItemType";
ItemType1.DataValueField = "ID";
ItemType1.DataBind();
con.Close();
}
}
// Add a non selectable "Select Item" row at the top of the dropdown list
ItemType1.Items.Insert(0, new ListItem("--Select Item--", "0"));
}
}
protected void ItemType1_SelectedIndexChanged(object sender, EventArgs e)
{
//
// *** Stuff needs to go here in order to continue with the following conditional statement ***
//
if (ItemType1.SelectedValue == "Green")
{
BinResultTest.Text = "<div class='greenBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should be disposed of in a <strong>green bin</strong>.</p></div>";
}
else if (ItemType1.SelectedValue == "Black")
{
BinResultTest.Text = "<div class='blackBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should be disposed of in a <strong>black bin</strong>.</p></div>";
}
else
{
BinResultTest.Text = "<div class='noBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should <strong>NOT</strong> be disposed of in a green or black bin.</p></div>";
}
}
}
What do I need to do to get the conditional statement to work? I presume I need to run another database query - something like the following:
SELECT BinType FROM NF_WhatWasteWhere WHERE ID=" + ItemType1.DataValueField
However, I'm not sure how to code this to establish the connection and return the result.
Any help appreciated.
Thanks.
Edit***
Okay then in protected void ItemType1_SelectedIndexChanged(object sender, EventArgs e)
You can do something similar to what you did with your first query but use an OdbcDataReader
string binValue;
int idHolder = ItemType1.SelectedValue;
con.ConnectionString =System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_GRPAS_dev"].ConnectionString;
{
using (OleDbCommand cmd = new OleDbCommand("SELECT BinType FROM NF_WhatWasteWhere WHERE ID = #Id;"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Id",idHolder);
cmd.Connection = con;
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
if(!DBNull.Value.Equals(reader["BinType"]))
{
binValue = Convert.ToString(reader["BinType"]);
}
}
con.Close();
//Then all your conditionals based off of binValue....
Something like this but maybe a bit more well writen.
I am changing a console app login over to a web based application and recieve the following error about an Unhandled exception.
In the console app I have the following line of code which resides in the StoredProcDemo class:
StoredProcDemo spd = new StoredProcDemo();
In the Web Application I have:
Login spd = new Login();
I am not sure what to change it over to. Could someone shed some insight thanks and maybe why? Thanks so much.
Here is the full code if needed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data.SqlTypes;
namespace GUI_Login
{
public partial class Login : System.Web.UI.Page
{
SqlConnection conn = null;
SqlParameter parmReturnValue;
Login spd = new Login();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
RunStoredProcParams();
}
public void RunStoredProcParams()
{
//run simple stored procure
spd.RunStoredProcParams();
int Result;
Result = -1;
conn = conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\UserDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True; Integrated Security=SSPI");
conn.Open();
try
{
//create and open a connection object
conn = conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\UserDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True; Integrated Security=SSPI");
conn.Open();
//Create the command object indentifying the stored procedure
SqlCommand cmd = new SqlCommand("PassParamUserID", conn);
//set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#FirstName", txtUserName.Text));
parmReturnValue = cmd.Parameters.AddWithValue("#UserId", SqlDbType.Int);
parmReturnValue.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
Result = Convert.ToInt32(cmd.Parameters["#UserId"].Value);
conn.Close();
// lblResult.Text = Result;
if (Result > 0)
{
lblResult.Text = ("User does exist in database");
}
else if (Result < 0)
{
lblResult.Text = ("Denied, try another user name");
}
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
Even ignoring RunStoredProcParams you'll get a stack overflow as soon as you try to create a new instance:
public partial class Login : System.Web.UI.Page
{
// Removed extraneous stuff...
Login spd = new Login();
}
Why do you want every instance of Login to have a reference to another instance of Login, which it creates immediately?
Basically the constructor is going to be called recursively until it goes bang.
What are you trying to do here, and why? In the console app you may well be creating an instance of StoredProcDemo, but I'm sure it wouldn't be within StoredProcDemo itself (as an instance variable initializer). Perhaps it's in Program or something similar? That would make more sense.
You run RunStoredProcParams() recursively indefinitely.
Comment out this line:
spd.RunStoredProcParams();
Also comment this one:
Login spd = new Login();