System.Data.SqlClient.SqlException error at asp.net - asp.net

I am new at asp.net. I was trying database connection. But I am getting this error. Please advice me.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs = "Data Source=.;Initial Catalog=test;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(cs);
SqlCommand comma = new SqlCommand("select * from try", con);
con.Open();
GridView1.DataSource = comma.ExecuteReader();
GridView1.DataBind();
con.Close();
}
}
}

The issue is with the connection string you are using.
Data Source=.;Initial Catalog=test;Integrated Security=SSPI
Check the SQL Server instance name running on your local.
Data Source=**.\YourInstanceName**;Initial Catalog=test;Integrated Security=SSPI
You can test your connection string validity by trying to add a connection in Server Explorer (Tools -> Connect to Server - VS2015).
Good luck

Related

I am building a website using ASP.Net & I encountered an 'invalid object name' error as shown. What is the reason behind this error?

I'm building a small website using ASP.Net & I encountered the following error.
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;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication_Exam_Website
{
public partial class OnlineAssessment : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from questionnaire";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sdr.Fill(dt);
Repeater1.DataSource = dt;
Repeater1.DataBind();
sqlconn.Close();
}
}
}
}
Error #Line 26: sdr.Fill(dt);:
Invalid object name 'questionnaire'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'questionnaire'.
Why am I getting this error?
P.S.: 'questionnaire' is the name of the SQL table I've created.
Connection string-->
<add name="Myconnection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\utopia\Desktop\Project\Us.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>

Retrieve name and image from database where image is stored as upload folder and reference is stored in database?

Trying the following code but could't get the desired result.
I have stored the image in the upload folder and its reference is saved in database while storing the data in the database from the admin side.
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;
using System.Configuration;
using System.Data;
namespace Admin
{
public partial class fetch : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs =
ConfigurationManager.ConnectionStrings["DBSC"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spUploadImage", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter ParamId = new SqlParameter()
{
ParameterName = "#Id",
Value = Request.QueryString["Id"]
};
cmd.Parameters.Add(ParamId);
con.Open();
byte[] Bytes = (byte[])cmd.ExecuteScalar();
string strBase64 = Convert.ToBase64String(bytes);
FileUpload1.ImageUrl = "data:image/png;base64, +strBase64";
}
}
}
}

How to add connection string dynamically in web.config

I have to create one application which will add connection string in web.config when user clicks on some control.
actually it runs fine,
But now together with it i have to run one SQL script which will create new database.
for that i have write following code..
now it gives me error as
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Web.Configuration;
using System.Collections.Generic;
public partial class connectionString : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnadd_Click(object sender, EventArgs e)
{
try
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
// System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
var section = config.GetSection("connectionStrings") as ConnectionStringsSection;
section.ConnectionStrings.Add(new ConnectionStringSettings(txtNAme.Text, txtNAme.Text, "System.Data.SqlClient"));
config.Save();
string sqlConnectionString = #"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ccwebgrity;Data Source=SURAJIT\SQLEXPRESS";
FileInfo file = new FileInfo(#"G:\AAA\SCRIPT.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
file.OpenText().Close();
}
catch (Exception ex)
{
}
}
}
Define the connection string in web.config
<ConnectionStrings>
<add name="student" connectionString="Server=student;Max Pool Size=300;Initial Catalog=studentDB;User ID=student;Password=st123dent;" providerName="System.Data.SqlClient"/>
</Connectionstrings>
Configuration is read only so you can not do it in obvious way like
ConfigurationManager.ConnectionStrings["student"].ConnectionString = "new value";

how to remove error Incorrect syntax near 'nvarchar'. Must declare the scalar variable "#"

I am getting this error Incorrect syntax near 'nvarchar'. Must declare the scalar variable "#". I am using the code as mentioned below . Here SACALOGIN.MDF is Database name admin_login is table name. User-Name and Password are table columns and admin1.aspx is another web page ...please help as it is giving me a great headache .....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.Configuration.Common;
using System.Web.Configuration.Internal;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection cn=new SqlConnection();
cn.ConnectionString =
WebConfigurationManager.ConnectionStrings["SACALOGIN.MDF"].ConnectionString;
cn.Open();
string sql="Select * from admin_login where ID=#[ID]";
SqlCommand cmd=new SqlCommand(sql,cn);
cmd.Parameters.AddWithValue("#[User-Name]",txtUserName.Text);
cmd.Parameters.AddWithValue("#Password",txtPWD.Text);
SqlDataReader dr=cmd.ExecuteReader();
bool found=false;
if(dr.Read())
{
found=true;
cn.Close();
if(found)
{
Response.Redirect("admin1.aspx");
}
else
lblMessage.Text="Sorry! Invalid User Id.";
}
}
}
You're using a 'ID' parameter , but the only parameters you're adding to your command are '#user-name' and '#Password'. Try to replace :
string sql="Select * from admin_login where ID=#[ID]";
SqlCommand cmd=new SqlCommand(sql,cn);
cmd.Parameters.AddWithValue("#[User-Name]",txtUserName.Text);
cmd.Parameters.AddWithValue("#Password",txtPWD.Text);
by :
string sql="Select * from admin_login where [ID]=#ID";
SqlCommand cmd=new SqlCommand(sql,cn);
cmd.Parameters.Add("#ID", SqlDbType.Int);
cmd.Parameters["#ID"].Value = userID;
of course, replace this last 'userID' by whatever your userid variable is named...
I dont think your code will ever work.
It should be something like this
SqlConnection cn=new SqlConnection();
cn.ConnectionString = W WebConfigurationManager.ConnectionStrings["SACALOGIN.MDF"].ConnectionString;
cn.Open();
string sql="Select * from admin_login where [User-Name] = #Username and Password= #Password";
SqlCommand cmd=new SqlCommand(sql,cn);
cmd.Parameters.AddWithValue("#Username",txtUserName.Text);
cmd.Parameters.AddWithValue("#Password",txtPWD.Text);
SqlDataReader dr=cmd.ExecuteReader();
bool found=false;

Asp.net how to solve the error

Im designing my web page, in that i have typed in the book id and typed Nameofthebook. and then click the button the stack of book are available is go to another page and then not available is display the error message is book is not available My project (Library management system)
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class Bookcheck : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string constr = null;
constr = ConfigurationManager.ConnectionStrings["librarymanagementconnetionstring"].ConnectionString;
SqlConnection cnn = new SqlConnection(constr);
cnn.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("SELECT*FROM BOOKREGISTRATIONDETAILS WHERE bookId='" + txtid.Text.Trim() + "'AND Nameofbook='" + txtnb.Text.Trim() + "'", constr);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
Response.Redirect("Issueofbook.aspx");
}
else
{
Msg.Text = "NO book available";
Msg.Visible = true;
}
}
}
Error:
Object reference not set to an instance of an object.
I noticed that in librarymanagementconnetionstring, connection is spelled incorrectly. Is this the correct entry in your web.config for the connection string?
I'd say that it's the line
if (ds.Tables[0].Rows.Count > 0)
that giving the error.
If your DataSet has no tables then ds.Tables could be null.
If that's a possibility then you need to code for that.
If there are no rows ds.Tables[0].Rows won't be null and your test should work.
Change
if (ds.Tables[0].Rows.Count > 0)
to
if(ds.HasRows)

Resources