System.InvalidOperationException connecting to SQLExpress database? - asp.net

protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source= LAPTOP-KVFS4TPD\\SQLEXPRESS; Database= PayPalDB; UID= sa; PWD= 061199081298;");
SqlCommand cmd = new SqlCommand("SP_DBASE", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.Parameters.AddWithValue("#FirstName", FNtxt.Text);
cmd.Parameters.AddWithValue("#MiddleName", MNtxt.Text);
cmd.Parameters.AddWithValue("#LastName", LNtxt.Text);
cmd.Parameters.AddWithValue("#Email", Emailtxt.Text);
cmd.Parameters.AddWithValue("#Email2", Email2txt.Text);
cmd.Parameters.AddWithValue("#BirthDate", txtDate.Text);
cmd.Parameters.AddWithValue("#Address", Addresstxt.Text);
cmd.Parameters.AddWithValue("#CreditCardNo", CCNtxt.Text);
cmd.Parameters.AddWithValue("#CVVNo", CVVtxt.Text);
cmd.Parameters.AddWithValue("#Gender", GenderRDL.SelectedItem);
cmd.Parameters.AddWithValue("#Country", DDLCountry.SelectedItem);
cmd.ExecuteNonQuery();
con.Close();
Server.Transfer("UserLogIn.aspx", true);
}
enter image description here
The error is in con.Open();:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code".

Your connection string is wrong.
This is the correct syntax for SQLExpress connection strings:
Data Source=.\SQLEXPRESS;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
In your case:
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;Database=PayPalDB;UID=sa;PWD=061199081298;");

Related

Con.open error ASP.NET in Godaddy Plesk Hosting

I am struggling with my new website which I recently uploaded on Godaddy server.
Con.open() is the line which is causing error : The wait operation timed out
My Code: file.aspx.cs
SqlConnection con = new SqlConnection(#"Data Source=databaseserverurl;Network Library=DBMSSOCN;Initial Catalog=mydatabase;User ID=something;Password=something;");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (con.State != ConnectionState.Open) {
con.Open();
}
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from mytable";
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
}
For MySQL
You should use MySqlConnection, not SqlConnection.
For SQL Server
Most likely your databaseserverurl is wrong. Make sure your connection string corresponds to the one you have in the control panel. See https://de.godaddy.com/help/find-your-connection-strings-3323.
To ensure, open Sql Server Management Tool (or your favorite sql tool) and login your db with same server, user and password.

register button has no function

Suddenly my register button is not performing any action other that validations. any idea?
here is my registration.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection con = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlCommand cmd = new SqlCommand();
protected void btnSubmit_Click(object sender, EventArgs e)
{
if(Page.IsValid)
{
cmd.Connection = con; //assigning connection to command
cmd.CommandType = CommandType.Text; //representing type of command
cmd.CommandText = "INSERT INTO UserData values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
//adding parameters with value
cmd.Parameters.AddWithValue("#Username", txtUser.Text);
cmd.Parameters.AddWithValue("#Firstname", txtFN.Text);
cmd.Parameters.AddWithValue("#Lastname", txtLN.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Password", (txtPW.Text));
cmd.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
cmd.Parameters.AddWithValue("#Zip", txtZip.Text);
cmd.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
con.Open(); //opening connection
cmd.ExecuteNonQuery(); //executing query
con.Close(); //closing connection
label_register_success.Text = "Registered Successfully..";
}
else
{
label_register_success.Text = "Please check the registration errors";
}
}
protected void ValidateUserName(object source, ServerValidateEventArgs arguments)
{
string UserName = arguments.Value;
using (SqlConnection con = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM UserData WHERE Username=#Username", con);
cmd.Parameters.AddWithValue("#Username", UserName);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
arguments.IsValid = false;
}
else
{
arguments.IsValid = true;
}
}
}
protected void ValidateEmail(object source, ServerValidateEventArgs arguments)
{
string Email = arguments.Value;
using (SqlConnection con = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM UserData WHERE Email=#Email", con);
cmd.Parameters.AddWithValue("#Email", Email);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
arguments.IsValid = false;
}
else
{
arguments.IsValid = true;
}
Its not performing the successful registration and the validations for the repeated username and email. please help me out, thanks!
Try triggering the validation via:
Page.Validate();
And pass in any validation groups you use as the parameter (if applicable) before checking IsValid, and see if that detects the errors. I assume your Validate methods are called from CustomValidator controls?

Error in running simple Web application "System.ComponentModel.Win32Exception: The network path was not found"

I tried to run this code but it raise an error at con.Open() method
"System.ComponentModel.Win32Exception: The network path was not found"
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs = "server = (localdb)\v11.0 ; database = DepartmentsAndEmployees ; integrated security=true";
SqlConnection conn = new SqlConnection(cs);
SqlCommand com = new SqlCommand("select * from Employees", conn);
conn.Open();
GridView1.DataSource = com.ExecuteReader();
GridView1.DataBind();
conn.Close();
}
}
This is because it can not find the server. There is something wrong with your connection string.
Try this connection string builder:
http://www.developerfusion.com/tools/sql-connection-string/
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx

stored procedure to delete entire table

I want to delete all the rows of a table on a button click.the stored procedure is as follows:
create proc spTest
as
begin
Delete from tblTest
end
The code-behind is as follows:
protected void Button3_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["EasyRozMoney_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTest", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
lblStatus.Text = "Tasks Deleted Successfully.";
}
}
but the table remains unaffected although the label shows all tasks deleted successfully. What is the problem? I know something is very silly that I am doing.
PS: I don't want to use Truncate.
You have created Command but did not execute it. You have to call ExecuteNonQuery in order to exeucte the Command
As a addition note, put the code in try-catch block so that your application does not terminated in case of exception
protected void Button3_Click(object sender, EventArgs e)
{
try
{
string CS = ConfigurationManager.ConnectionStrings["EasyRozMoney_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTest", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
lblStatus.Text = "Tasks Deleted Successfully.";
}
}
catch(Exception ex)
{
lblStatus.Text = "Tasks could not be deleted, Error " + ex.Message;
}
}
You have to execute the query using ExecuteNonQuery command.
protected void Button3_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["EasyRozMoney_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTest", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
lblStatus.Text = "Tasks Deleted Successfully.";
}
}
You are never acutally executing your query.
Call it like this:
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTest", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
/*new:*/
cmd.ExecuteNonQuery();
lblStatus.Text = "Tasks Deleted Successfully.";
}
You are forgoted to execute the command.
add this cmd.ExecuteNonQuery(); to Button3_Click event
protected void Button3_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["EasyRozMoney_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTest", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
if(cmd.ExecuteNonQuery()>0)
{
lblStatus.Text = "Tasks Deleted Successfully.";
}
else
{
lblStatus.Text = "Unable to Delete tasks";
}
}
}

{"Object reference not set to an instance of an object."}

Creating a ASP.NET form with C#, i am facing this error i don't know what is the error with it. Its all doing fine but when i push the save Button it gives me this error:
NulllRefrenceException was unhandled by user code
{"Object reference not set to an instance of an object."}
Object reference not set to an instance of an object.
Code:
protected void Button8_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlAddSave"].ConnectionString;
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from DisplayPP";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, " DisplayPP ");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow drow = ds.Tables["DisplayPP"].NewRow();
drow["website"] = web.Text;
drow["country"] = DropDownList1.SelectedItem.Text;
drow["contact"] = TextBox144.Text;
drow["cat"] = TextBox145.Text;
drow["traff"] = TextBox146.Text;
more text boxes as above
ds.Tables["DisplayPP "].Rows.Add(drow);
da.Update(ds, " DisplayPP ");
string script = #"<script language=""javascript"">
alert('Information have been Saved Successfully.......!!!!!.');
</script>;";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
}
please help.
Connection String:
<add name="sqlAddSave" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\PPTableDisplay.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
Exception
Exception Details: System.NullReferenceException was unhandled by user
code HResult=-2147467261 Message=Object reference not set to an
instance of an object. Source=TestCRole StackTrace: at
TestCRole._Default.Button8_Click(Object sender, EventArgs e) in
c:\Users\xxxxx\Documents\Visual Studio
2012\Projects\WindowsAzure2\TestCRole\Default.aspx.cs:line 60 at
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) at System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
ds.Tables["DisplayPP "].Rows.Add(drow);
should be this
ds.Tables["DisplayPP"].Rows.Add(drow);

Resources