Returning output values from a stored procedure to asp.net - asp.net

I have an output value in my procedure called result, I want to make an if condition in asp.net that checks if result = 1 and print a statement
public partial class ManagerViewTasks : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection( #"data source= DODO\SQLEXPRESS; " +
"Initial Catalog = Company_103; Integrated Security = True");
protected void Button1_Click(object sender, EventArgs e)
{
if (sqlcon.State == System.Data.ConnectionState.Closed)
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("MG_Reviews_Task",sqlcon);
sqlcmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlcmd.Parameters.Add("#result ", SqlDbType.Int).Direction=ParameterDirection.Output;
sqlcmd.Parameters.AddWithValue("#re ", Txtname.Text.Trim());
sqlcmd.Parameters.AddWithValue("#task", TextBox2.Text.Trim());
sqlcmd.Parameters.AddWithValue("#proj",TextBox3.Text.Trim());
sqlcmd.Parameters.AddWithValue("#company",TextBox4.Text.Trim());
sqlcmd.Parameters.AddWithValue("#manager",TextBox5.Text.Trim());
sqlcmd.Parameters.AddWithValue("#res",TextBox6.Text.Trim());
sqlcmd.Parameters.AddWithValue("#deadline ",TextBox7.Text.Trim());
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
}
}

SqlParameter result = New SqlParameter();
result.ParameterName = "result";
result.Value = 0;
result.Size = 1;
result.Direction = ParameterDirection.Output;
sqlcmd.Parameters.Add(result);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
//Check result value here
if (result.value == 1){
//Do something;
}

Related

Using a checkbox to change an existing database value

I currently have a checkbox that remains checked or unchecked based on the value in the database. I want the checkbox to be able to change dynamically, so that if it's checked upon loading the page and I change it to unchecked, it will change the database value as well as redirect to a different page. Right now I am unable to change the database value and redirect to a different page. I have autopost back set to true currently.
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection dataConnection = new SqlConnection(#"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8"))
using (SqlCommand dataCommand =
new SqlCommand("select SportHasPositions from Sport Where Sport_Id = #Sport_Id", dataConnection))
{
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "#Sport_Id";
param2.Value = Session["SportID"];
dataCommand.Parameters.Add(param2);
dataConnection.Open();
sportHasPositions = dataCommand.ExecuteScalar().ToString();
}
if (sportHasPositions == "No")
{
CheckBox1.Checked = true;
Panel1.Visible = false;
}
if (sportHasPositions == "Yes")
{
CheckBox1.Checked = false;
Panel1.Visible = true;
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == false)
{
String conString = #"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8";
SqlConnection con = new SqlConnection(conString);
//create a command behavior object
String cmdString = "UPDATE Sport SET SportHasPositions = #SportHasPositions WHERE Sport_Id = #Sport_Id";
SqlCommand cmd = new SqlCommand(cmdString, con);
SqlParameter param0 = new SqlParameter();
param0.ParameterName = "#SportHasPositions";
param0.Value = "Yes";
cmd.Parameters.Add(param0);
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "#Sport_Id";
param1.Value = Session["SportID"];
cmd.Parameters.Add(param1);
int added = 0;
try
{
con.Open();
added = cmd.ExecuteNonQuery();
}
catch (Exception err)
{
// Output.Text = err.Message;
}
finally
{
con.Close();
}
Response.Redirect("Pick Positions.aspx");
}
if (CheckBox1.Checked == true)
{
String conString = #"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8";
SqlConnection con = new SqlConnection(conString);
//create a command behavior object
String cmdString = "UPDATE Sport SET SportHasPositions = #SportHasPositions WHERE Sport_Id = #Sport_Id";
SqlCommand cmd = new SqlCommand(cmdString, con);
SqlParameter param0 = new SqlParameter();
param0.ParameterName = "#SportHasPositions";
param0.Value = "No";
cmd.Parameters.Add(param0);
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "#Sport_Id";
param1.Value = Session["SportID"];
cmd.Parameters.Add(param1);
int added = 0;
try
{
con.Open();
added = cmd.ExecuteNonQuery();
}
catch (Exception err)
{
// Output.Text = err.Message;
}
finally
{
con.Close();
}
}
}
The problem is that the asp.net life cycle runs the Page_Load event before the CheckBox1_CheckedChanged event. Since in your Page_Load, you are setting the checkbox, even if the user changed it, the Page_Load changes it back before the CheckBox1_CheckedChanged can change it in the database. To fix this you can use the Page.IsPostBack
flag so the Page_Load only sets the Checkbox on the initial page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
using (SqlConnection dataConnection = new SqlConnection(#"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8"))
using (SqlCommand dataCommand =
new SqlCommand("select SportHasPositions from Sport Where Sport_Id = #Sport_Id", dataConnection))
{
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "#Sport_Id";
param2.Value = Session["SportID"];
dataCommand.Parameters.Add(param2);
dataConnection.Open();
sportHasPositions = dataCommand.ExecuteScalar().ToString();
}
if (sportHasPositions == "No")
{
CheckBox1.Checked = true;
Panel1.Visible = false;
}
if (sportHasPositions == "Yes")
{
CheckBox1.Checked = false;
Panel1.Visible = true;
}
}
}

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

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();
}

Gridview does not show SQL Server database records

I'm designing a web system for my fyp.
I use SqlDependency to get table change info from cache.
I used SqlDataAdapter, dataSet and gridview, but it doesn't show any result on screen.
Can you tell me where the problem is in my code?
protected void refresh_Click(object sender, EventArgs e)
{
if (Cache["shipOrders"] == null)
{
gvshipOrders.DataSource = Cache["shipOrders"];
gvshipOrders.DataBind();
lblOrderNotification.Text = "last order recived at " + DateTime.Now.ToString();
}
else
{
string xconnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection sqlCon = new SqlConnection(xconnectionString);
SqlDataAdapter da = new SqlDataAdapter("viewOrders", sqlCon);
DataSet ds = new DataSet();
da.Fill(ds);
SqlCacheDependency XsqlcacheDependecy = new SqlCacheDependency("secaloTest1", "customerShipOrder");
//caching shipOrders table data
/*
Cache.Insert("shipOrders", ds, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
another overloaded method is used */
Cache.Insert("shipOrders", ds, XsqlcacheDependecy);
gvshipOrders.DataSource = ds;
gvshipOrders.DataBind();
lblOrderNotification.Text = "orders retrived from database at " + DateTime.Now.ToString();
}
}
I've found the problem,
public partial class OrderProccessing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["email"] == null)
{
Response.Redirect("Default.aspx");
}
else
{
string value = Session["email"].ToString();
Classes.AddAddress addcuid = new Classes.AddAddress(value);
txtstaffname.Text = addcuid.addStaffName().ToString();
txtstaffID.Text = addcuid.fetchStaffID().ToString();
}
}
protected void refresh_Click(object sender, EventArgs e)
{
if (Cache["shipOrders"] != null)
{
myGrid.DataSource = Cache["ShipOrders"];
myGrid.DataBind();
lblOrderNotification.Text = "last order recived at " + DateTime.Now.ToString();
}
else
{
string xconnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection sqlCon = new SqlConnection(xconnectionString);
SqlDataAdapter da = new SqlDataAdapter("viewOrders", sqlCon);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
SqlCacheDependency XsqlcacheDependecy = new SqlCacheDependency("secaloTest1", "customerShipOrder");
//caching shipOrders table data
/*
Cache.Insert("shipOrders", ds, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
another overloaded method is used */
Cache.Insert("shipOrders", ds, XsqlcacheDependecy);
myGrid.DataSource = ds;
myGrid.DataBind();
lblOrderNotification.Text = "orders retrived from database at " + DateTime.Now.ToString();
}
}
}

paging and sorting in grid view

i have a code performing paging and sorting in grid view.
(bing_grid is user defined function)
public void bind_grid()
{
con = new SqlConnection();
con.ConnectionString = "Data Source=STIRAPC105;InitialCatalog=anitha;Integrated Security=True";
con.Open();
SqlDataAdapter sqa = new SqlDataAdapter("select * from employees", con);
DataSet ds = new DataSet();
sqa.Fill(ds);
DataTable mytab = ds.Tables[0];
GridView1.DataSource = mytab;
GridView1.DataBind();
//con.Close();
}
code for paging
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind_grid();
}
code for sorting
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = GridView1.DataSource as DataTable;
if (dt != null)
{
DataView dataview = new DataView(dt);
dataview.Sort = e.SortExpression + " " + sort_grid(e.SortDirection);
GridView1.DataSource = dataview;
GridView1.DataBind();
}
}
user defined code for sorting
public string sort_grid()
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
paging works, Errors was:
1. "no overload for method 'sort_grid' takes 1 argument" (dataview.Sort = e.SortExpression + " " + sort_grid(e.SortDirection);)
2.The name 'sortDirection does not exist in the current context. (switch (sortDirection))
Help me friends.
this method:
public string sort_grid()
takes no arguments but you are trying to call it with e.SortDirection:
dataview.Sort = e.SortExpression + " " + sort_grid(e.SortDirection);
You must change the signature of sort_grid() to
sort_grid(SortDirection sortDirection)
This will also solve your second problem, which you are trying to use sortDirection variable, before declaring it in the method sort_grid.

Resources