ASP.NET Connection with Oracle DB - asp.net

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.

Related

How to use local variable of Page_OnLoad method in OnClick event in asp.net C#

I am designing a website in which I need to update a table Company in my database through CompanyDetails page with respect to the auto increment field CompanyID which is being passed through Query string from previous page named Company and only one button is there for insert and update. So my problem is I am unable to get the value of Companyid of Page_OnLoad event in SaveButtonClick event.
Note: I have already tried Session and View state, IsPostBack but in Onclick event even their value are not being maintained and are updated to 0 or null.
Here is my code......(Please ignore my coding mistakes)
using System;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
public partial class CompanyDetails : System.Web.UI.Page
{
int Companyid = 0;
string cmdName = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Companyid = Convert.ToInt32(Request.QueryString["CompanyID"]);
cmdName = Request.QueryString["CommandType"];
Session["something"] = Companyid;
}
if (cmdName == "Details")
{
BindTextBoxvalues();
}
}
protected void SaveButton_Click(object sender, EventArgs e)
{
string x = Session["something"].ToString();
try
{
if (SaveButton.Text == "Save")
{
SqlCommand cmd = new SqlCommand();
String mycon = "Data Source=.; Initial Catalog=something; Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
cmd = new SqlCommand("spInsertCompany", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CompanyName", SqlDbType.VarChar).Value = Name.Text;
cmd.Parameters.Add("#CompanyCode", SqlDbType.VarChar).Value = CompanyCode.Text;
cmd.Parameters.Add("#LegalName", SqlDbType.VarChar).Value = LegalName.Text;
cmd.Parameters.Add("#TaxID", SqlDbType.Int).Value = TaxID.Text;
cmd.Parameters.Add("#BusinessPhone", SqlDbType.VarChar).Value = BusinessPhone.Text;
cmd.Parameters.Add("#Extension", SqlDbType.VarChar).Value = Extension.Text;
cmd.Parameters.Add("#FaxNumber", SqlDbType.VarChar).Value = FaxNumber.Text;
cmd.Parameters.Add("#Description", SqlDbType.VarChar).Value = Description.Value;
bool isstatus = IsActiveCheckBox.Checked;
cmd.Parameters.Add("#Status", SqlDbType.Int).Value = Convert.ToInt32(isstatus);
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
Response.Write("<script language='javascript'>window.alert('Saved Successfully.');window.location='Company.aspx';</script>");
}
else if (SaveButton.Text == "Update")
{
SqlCommand cmd = new SqlCommand();
String mycon = "Data Source=.; Initial Catalog=something; Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
cmd = new SqlCommand("spUpdateCompany", con);
cmd.CommandType = CommandType.StoredProcedure;
int a = Convert.ToInt32(Companyid);
// I need the value here but it is being updated to zero here.
cmd.Parameters.Add("#CompanyID", SqlDbType.Int).Value = Companyid;
cmd.Parameters.Add("#CompanyName", SqlDbType.VarChar).Value = Name.Text;
cmd.Parameters.Add("#CompanyCode", SqlDbType.VarChar).Value = CompanyCode.Text;
cmd.Parameters.Add("#BusinessPhone", SqlDbType.VarChar).Value = BusinessPhone.Text;
cmd.Parameters.Add("#Extension", SqlDbType.VarChar).Value = Extension.Text;
cmd.Parameters.Add("#FaxNumber", SqlDbType.VarChar).Value = FaxNumber.Text;
cmd.Parameters.Add("#TaxID", SqlDbType.Int).Value = TaxID.Text;
cmd.Parameters.Add("#LegalName", SqlDbType.VarChar).Value = LegalName.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
Response.Write("<script language='javascript'>window.alert('Updated Successfully.');window.location='Company.aspx';</script>");
}
}
catch (SqlException ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message",
"alert('Oops!! following error occured : " + ex.Message.ToString() + "');", true);
}
}
protected void CancelButton_Click(object sender, EventArgs e)
{
Response.Redirect("Company.aspx");
}
private void BindTextBoxvalues()
{
SaveButton.Text = "Update";
string constr = "Data Source=.; Initial Catalog=something; Integrated Security=True";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("select * from Company where CompanyID=" + Companyid, con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Name.Text = dt.Rows[0][1].ToString();
CompanyCode.Text = dt.Rows[0][2].ToString();
LegalName.Text = dt.Rows[0][15].ToString();
TaxID.Text = dt.Rows[0][14].ToString();
BusinessPhone.Text = dt.Rows[0][3].ToString();
Extension.Text = dt.Rows[0][13].ToString();
FaxNumber.Text = dt.Rows[0][12].ToString();
Description.Value = dt.Rows[0][4].ToString();
IsActiveCheckBox.Checked = Convert.ToBoolean(dt.Rows[0][11]);
}
}
Any values stored in local variables need to be read from Request on every postback.
So do following
int Companyid = 0;
string cmdName = null;
protected void Page_Load(object sender, EventArgs e)
{
Companyid = Convert.ToInt32(Request.QueryString["CompanyID"]);
cmdName = Request.QueryString["CommandType"];
if (!IsPostBack)
{
if (cmdName == "Details")// be sure about string case
{
BindTextBoxvalues();
}
}
}
Or make viewstate properties
If you want to have your property available on the PostBack, do not use !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
Companyid = Convert.ToInt32(Request.QueryString["CompanyID"]);
}

ASP.Net Server prints data from DB but won't write to DB

I have an issue with the connectionstring or something similiar I assume. since data is printed from DB but won't write to DB using the INSERT Query string.
here's the .cs code part:
protected void Page_Load(object sender, EventArgs e)
{
Load_Data();
}
protected void Load_Data()
{
DataTable dtUsers = new DataTable();
// connect to sql
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
// create sql
string sql = "SELECT Username, Fullname, Email FROM Users;";
// command
SqlCommand cmd = new SqlCommand(sql, con);
// load data to dt
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtUsers.Load(reader);
con.Close();
// print data to gridview
GridView1.DataSource = dtUsers;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
// connect to sql
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
// create query
string sql = "INSERT INTO Users (UserName,Passowrd,Email,FullName) VALUES ('" + txtUsername.Text + "','"+ txtPwd.Text + "','"+ txtEmail.Text + "','" + txtFullName.Text + "');";
// command
SqlCommand cmd = new SqlCommand(sql, con);
// save data to db
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
thank you!

how to display and update data in textbox of asp.net by using stored procedure?

i want to update user information .so first i want when user click on update button than all the field display with their values in text box so that user can able to edit his profile.
i got an error :Procedure or function 'updatefill' expects parameter '#email', which was not supplied.
please help me out from this error...
Thank you.
public partial class updateuser : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cnstr"].ConnectionString);
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
SqlDataReader dr;
string str1="";
protected void Page_Load(object sender, EventArgs e)
{
{
con.Open();
cmd = new SqlCommand("updatefill", con);
cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds,"registr");
fname.Text = ds.Tables["registr"].Rows[0]["fname"].ToString();
lname.Text = ds.Tables["registr"].Rows[0]["lname"].ToString();
uid.Text = ds.Tables["registr"].Rows[0]["email"].ToString();
pwd.Text = ds.Tables["registr"].Rows[0]["password"].ToString();
pwd1.Text = ds.Tables["registr"].Rows[0]["confirmpassword"].ToString();
mbl.Text = ds.Tables["registr"].Rows[0]["mobile"].ToString();
con.Close();
}
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked)
{
str1 = "Male";
}
else if (RadioButton2.Checked)
{
str1 = "Female";
}
else
{
str1 = "please select gender";
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("update_user_details", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#fname", SqlDbType.VarChar).Value = fname.Text;
cmd.Parameters.Add("#lname", SqlDbType.VarChar).Value = lname.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = uid.Text;
cmd.Parameters.Add("#mobile", SqlDbType.VarChar).Value = mbl.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = pwd.Text;
cmd.Parameters.Add("#confirmpassword", SqlDbType.VarChar).Value = pwd1.Text;
cmd.Parameters.Add("#gender", str1);
dt = new DataTable();
da = new SqlDataAdapter(cmd);
da.Fill(dt);
int s = Convert.ToInt32(dt.Rows[0][0]);
if (s == 1)
{
errmsg.Text = "Update Successfull";
Response.Redirect("userhome.aspx");
}
else
{
errmsg.Text = "Update Faild";
con.Close();
}
ALTER PROCEDURE [dbo].[updatefill]
#email varchar(50)
AS
BEGIN
select * from registr where email=#email
END
Here is an example using the Reader:
String connStr = ConfigurationManager.ConnectionStrings["DB1"].ConnectionString;
String cmdStr = "SELECT [col2],[col3] FROM [Table1] WHERE [col1]=#col1;";
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(("updatefill", con);
{
cmd.CommandType = C0mmandType.StoredProcedure;
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
fname.Text = rdr[0];
lname.Text = rdr[1]
uid.Text = rdr[2]
pwd.Text = rdr[3]
pwd1.Text = rdr[4];
mbl.Text = rdr[5];
}
}
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}

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";
}
}
}

Why session is getting null while inserting the data and getting the data from SQL LITE

I have written a code to insert the data to SQL LITE database as follows
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
count = 0;
Session["x"] = "session value";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string path = Server.MapPath("bin/sampldb.db");
SQLiteConnection conn = new SQLiteConnection("Data Source=" + path + "");
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
string txt="insert into stu values("+TextBox1.Text +",'"+TextBox2.Text+"')";
cmd.CommandType = CommandType.Text;
cmd.CommandText = txt;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Label1.Visible = true;
Label1.Text = "Error:" + ex.Message;
}
}
After inserting while retrieving data Session is getting null I don't know why
protected void Button2_Click(object sender, EventArgs e)
{
if (Session["x"] != null) // Getting Null here
{
Label1.Visible = true;
Label1.Text = Session["x"].ToString();
DataSet m_oDataSet = new DataSet();
string path = Server.MapPath("bin/sampldb.db");
SQLiteConnection conn = new SQLiteConnection("Data Source=" + path + "");
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
string txt = "select * from stu";
cmd.CommandText = txt;
SQLiteDataAdapter adp = new SQLiteDataAdapter();
adp.SelectCommand = cmd;
adp.Fill(m_oDataSet);
GridView1.DataSource = m_oDataSet.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Visible = true;
Label1.Text = "Error:" + ex.Message;
}
finally
{
conn.Close();
}
}
}
The same code when tested in Sql server 2008 works fine
protected void BtnSqlInsert_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cnstr);
con.Open();
SqlCommand cmd = new SqlCommand("Insert into [User] values ('" + TextBox1.Text + "','" + TextBox2.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
}
protected void BtnSqlGet_Click(object sender, EventArgs e)
{
if (Session["x"] != null) //Able to get session here
{
Label1.Visible = true;
Label1.Text = Session["x"].ToString();
}
}
My sql lite path is from Bin folder as shown in image
your app writes to DB (which is in BIN folder). That causes app restart => in-proc session gets lost. You should NOT solve the consequence (by using StateServer mode), you should fix the original reason - move db file into another folder, away from BIN folder.

Resources