The ConnectionString property has not been initialized - asp.net

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.

Related

How to get a table on a new web page when a button is Clicked

This is my one tag:
<asp:Button ID="button" runat="server" Text="ShowOrder" onclick="newTab" />
This is my 'aspx.cs' which will be called when button is clicked
protected void newTab(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?id="+txtSearchCustomerByID.Value);
}
What I want is to print my sql table on loaded web tab (new page) when it gets loaded.
My stored procedure is displaying the data of my table where id is equal to "id entered by user in textbox".
Now,
protected void Page_Load(object sender, EventArgs e)
{
int id_no = int.Parse(Request.QueryString["id"]);
if (Page.IsPostBack)
{
showOrders(id_no);
}
}
Now what should I have in 'Default2.aspx' so that I will get my table by using,
public void showOrders(int id)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand("showOrdersSP", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", id);
con.Open();
.......
}
}
I need to use DataTable
So simply when I clicked, I will get data table on new page
You can refer below code:
public void showOrders(int id)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
DataTable dt = new DataTable();
SqlParameter[] p1 = new SqlParameter[1];
p1[0] = new SqlParameter("#id", id);
dt= getRecords_table("showOrdersSP", p1); // you will get your DataTable here
}
}
// Common Method for FillYour Tables
private DataTable getRecords_table(string spname, SqlParameter[] para)
{
string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["connName"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(connectionstring);
SqlDataAdapter ad = new SqlDataAdapter(spname, con);
ad.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
ad.SelectCommand.Parameters.AddRange(para);
con.Open();
ad.Fill(dt);
con.Close();
return dt;
}
Hope it will helps you
Thanks

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?

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

SQL simple registration - all time exception

i have problem with registration in ASP.NET.
When i try to add new user to table in sql i catch exception. No idea what is wrong, in my opinion code is correct.
Look at this:
public partial class Registeration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RejConnectionString"].ConnectionString);
con.Open();
string cmdStr="Select count(*) from Registration where UserName='" + TextBoxUN.Text + "'";
SqlCommand userExist = new SqlCommand(cmdStr, con);
int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
con.Close();
if (temp == 1)
{
Response.Write("Already exist.<br /> Change another nickname.");
}
}
}
protected void Wyślij_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RejConnectionString"].ConnectionString);//połączenie z bazą
con.Open();
string insCmd = "Insert into Registration (UserName, Password, EmailAddress, FullName, Country) values (#UserName, #Password, #EmailAddress, #FullName, #Country)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#UserName,", TextBoxUN.Text);
insertUser.Parameters.AddWithValue("#Password", TextBoxPass.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBoxEA.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBoxFN.Text);
insertUser.Parameters.AddWithValue("#Country", DropDownListCountry.SelectedItem.ToString());
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("/Account/Login.aspx");
}
catch (Exception er)
{
Response.Write("<b>STH bad happened :( Try again</b>");
}
finally
{
}
}
}
well
1. DO NOT DO REDIRECTs inside of TRY!!!! Response.Redirect("/Account/Login.aspx"); NO NO!!
2. if you do with finally DO THE CLOSE connection there
I will redo this try Open connection to be inside as well

I have created a new thread and try to populate it .But the grid is not visible in browser

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ThreadStart st = new ThreadStart(Populate);
Thread td = new Thread(st);
td.Start();
}
}
private void Populate()
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("select * from dbo.sales", con);
con.Open();
SqlDataReader rdr = com.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
}
I think this is because your new thread is still fetching data when the page is rendered.
So better do it like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Populate();
}
}
private void Populate()
{
using(SqlConnection con = new SqlConnection(conStr))
{
using(SqlCommand com = new SqlCommand("select * from dbo.sales", con))
{
con.Open();
SqlDataReader rdr = com.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
}
}
}
Try changing the Code:
private void Populate()
{
using(var con = new SqlConnection(conStr))
{
using(var com = new SqlCommand("select * from dbo.sales", con))
{
con.Open();
com.CommandType= CommandType.Text;
using(var rdr = com.ExecuteReader())
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
}
}
}
If it doesn't works, try to removing new thread and use delegates to call the method Populate, if you want so.
Here is a link for using Asynchronous Methods. This is not the actual thing you required,but it will give you a good insight , how to use delegates to call a method asynchronously.
For asynchronous tasks, you can use PageAsyncTask class.
In this case you must add Async="True" attribute.
<%#Page Async="True" ... %>

Resources