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);
Related
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;");
I do not understand why I have this error message. No code is used for the connection, only an SQLDatasource and a grid view. I am using this code:
protected void Page_Load(object sender, EventArgs e)
{
try
{
using(OracleConnection conn = new OracleConnection("....."))
using(OracleCommand cmd = new OracleCommand("select * from t1", conn))
{
conn.Open();
using(OracleDataReader reader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
ListBox1.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
Label1.Text=ex.Message;
}
}
First you have install oracle data access client and then try this
following code
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source = DESCRIPTION = " +
"(ADDRESS = (PROTOCOL = TCP)(HOST = ho
List item
st_name)(PORT = 1521))" +
"(CONNECT_DATA =" +
" (SERVER = DEDICATED)" +
" (SERVICE_NAME = your_service_name)" +
")" + ");User Id = ID;Password=Password;";
Oracle.DataAccess.Client.OracleConnection con = new Oracle.DataAccess.Client.OracleConnection();
con.ConnectionString = connectionString;
con.Open();
Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand();
cmd.CommandText = "select ref_no from money_trn where ref_no=20170733";
cmd.Connection = con;
con.Close();
cmd.CommandType = System.Data.CommandType.Text;
Oracle.DataAccess.Client.OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
TextBox1.Text = dr.GetString(0);
}
You can't use SqlConnection for the Oracle!
First of all, you have to add connectionString into web.config to connection with Oracle.
Secondly, Add reference System.Data.OracleClient to your project.
Then, replace SqlConnection with OracleConnection. Everything, what you used with Sql, you have to replace with Oracle.
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
I want to insert data into database by using following code, but it causes an error that
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
I don't understand what can I do
Here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string con = "Data Source=Mir-pc;Initial Catalog=mir1;Integrated Security=True";
SqlConnection myconn = new SqlConnection(con);
string query = "insert into [Resevation] name,cellnumber,guest,tabl,date values(#name,#cellnumber,#guest,#tabl,#date)";
SqlCommand mycmd = new SqlCommand(query, myconn);
mycmd.Parameters.AddWithValue("#name", nameTextBox2);
mycmd.Parameters.AddWithValue("#cellnumber" ,cellTextBox3);
mycmd.Parameters.AddWithValue("#guest" , guestTextBox);
mycmd.Parameters.AddWithValue("#tabl", tableTextBox);
mycmd.Parameters.AddWithValue("#date", DateTextbox);
myconn.Open();
mycmd.ExecuteNonQuery();
myconn.Close();
}
Try like this :
protected void Button1_Click(object sender, EventArgs e)
{
string con = "Data Source=Mir-pc;Initial Catalog=mir1;Integrated Security=True";
SqlConnection myconn = new SqlConnection(con);
string query = "insert into [Resevation] name, cellnumber, guest, tabl, date values(#name, #cellnumber, #guest, #tabl, #date)";
SqlCommand mycmd = new SqlCommand(query,myconn);
mycmd.Parameters.AddWithValue("#name", nameTextBox2.Text);
mycmd.Parameters.AddWithValue("#cellnumber" ,cellTextBox3.Text);
mycmd.Parameters.AddWithValue("#guest" , guestTextBox.Text);
mycmd.Parameters.AddWithValue("#tabl", tableTextBox.Text);
mycmd.Parameters.AddWithValue("#date", DateTextbox);
myconn.Open();
mycmd.ExecuteNonQuery();
myconn.Close();
}
My connection string is placed in web.config as follows.
<connectionStrings>
<add name="empcon" connectionString="Persist Security Info=False;User ID=sa;Password=abc;Initial Catalog=db5pmto8pm;Data Source=SOWMYA-3BBF60D0\SOWMYA" />
</connectionStrings>
and the code of program is...
public partial class empoperations : System.Web.UI.Page
{
string constr = null;
protected void Page_Load(object sender, EventArgs e)
{
ConfigurationManager.ConnectionStrings["empcon"].ToString();
if (!this.IsPostBack)
{
fillemps();
}
}
public void fillemps()
{
dlstemps.Items.Clear();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["empcon"].ConnectionString);
con.ConnectionString = constr;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from emp";
cmd.Connection = con;
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem lt = new ListItem();
lt.Text = reader["ename"].ToString();
lt.Value = reader["empno"].ToString();
dlstemps.Items.Add(lt);
}
reader.Close();
}
catch (Exception er)
{
lblerror.Text = er.Message;
}
finally
{
con.Close();
}
i am totally new to programing....
i am able to run this application with er.message in label control as "the connection string property has not been initialized"
i need to retrieve the list of names of employees from the emp table in database into the dropdownlist and show them to the user...
can any one please fix it...
Where are you initializing your constr variable? It looks like you can leave that line out.
Also: just use using
using(SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["empcon"].ConnectionString)
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
//Rest of your code here
}
}
Side note: Don't use Select * From. Call out your columns: Select empname, empno From...
You are not assigning ConfigurationManager.ConnectionStrings["empcon"].ToString(); to string constr
protected void Page_Load(object sender, EventArgs e)
{
constr = ConfigurationManager.ConnectionStrings["empcon"].ToString();
...
will probably solve your problem for the time being.