I have an asp.net page with behind C# code.
I add a page Item in main page. then I used some web user control.
In one of them, when I use this Item in page_load. it has correct value, but when I use it in another private function in same web control, it has null value!
then I prefered to use a public string and set the value of that Item in it. but not working too.
public string ReqID0;
string Status0 { get; set; }
string Status = "";
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection sqlc4;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ReqID0 = Page.Items["ReqID"].ToString();
ReqIDLbl.Text = ReqID0;
...
second function (method) is:
private void Change_Status(string newStatus)
{
//ReqID0=Page.Items["ReqID"].ToString();
sqlc4 = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Request SET Status=#newStatus WHERE ID=#ReqID";
cmd.Parameters.AddWithValue("#newStatus", newStatus);
cmd.Parameters.AddWithValue("#ReqID", ReqID0);
cmd.Connection = sqlc4;
sqlc4.Open();
cmd.ExecuteNonQuery();
sqlc4.Close();
}
Page.Item refreshes with each post back and you have to add it every time your page refreshes ,,and as per your code here in Page_Load event
if (!this.IsPostBack)
{
ReqID0 = Page.Items["ReqID"].ToString();
ReqIDLbl.Text = ReqID0;
--Assigning of value is getting bypassed when your page does a post back and you get Null value in your Change_Status method. Try using Viewstate Instead.
Use the Items property to store objects with the same lifetime as the page request. MSDN
Update: try using ViewState.
if (!this.IsPostBack)
{
ViewState["ReqID"]= ReqIDLbl.Text;
//ReqID0 = Page.Items["ReqID"].ToString();
//ReqIDLbl.Text = ReqID0;
private void Change_Status(string newStatus)
{
//ReqID0=ViewState["ReqID"].ToString();
The global variables are created / intialized between postback in asp.net and they do not retain the values between postback as http is stateless protocol, you need to use ViewState for that.
public string ReqID0;
string Status0 { get; set; }
string Status = "";
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection sqlc4;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ReqIDLbl.Text = ReqID0;
ReqID0 = ViewState["ReqID0"].ToString();//ViewState
/*In case if the above code doesn't work use
ReqIDLbl.Text = ViewState["ReqID0"].ToString();*/
------
}
//Second Function
private void Change_Status(string newStatus)
{
ReqID0=ViewState["ReqID0"].ToString();
sqlc4 = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Request SET Status=#newStatus WHERE ID=#ReqID";
cmd.Parameters.AddWithValue("#newStatus", newStatus);
cmd.Parameters.AddWithValue("#ReqID", ReqID0);
cmd.Connection = sqlc4;
sqlc4.Open();
cmd.ExecuteNonQuery();
sqlc4.Close();
}
Hope This might give you the answer
Related
Hi im trying to insert data into my DataBase. The program runs but it never save the values!!.
heres the code:
using System.Data.SqlClient;
namespace Database_1._0
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"DataSource=LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Luis\documents\visual studio 2015\Projects\Database_1._0\Database_1._0\DB.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
DateTime dateTime = DateTime.UtcNow.Date;
string user = "1614258779876465426";
string pass = "3Cp5CeXrfghdfght";
string frecuencyCode = "ANNUAL";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void logo_Click(object sender, EventArgs e)
{
MessageBox.Show("Database_1._0 \nWritten by: Luis", "About");
}
private void button1_Click(object sender, EventArgs e)
{
cn.Open();
using (SieteWS SieteWS = new SieteWS())
{
Respuesta respuesta = SieteWS.SearchSeries(user, pass, frecuencyCode);
foreach (internetSeriesInfo seriesInfo in respuesta.SeriesInfos)
{
cmd.CommandText = "INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency]) VALUES (#SerieID, #SerieName, #SerieFrecuency)";
cmd.Parameters.AddWithValue("#SerieID", seriesInfo.seriesId);
cmd.Parameters.AddWithValue("#SerieName", seriesInfo.spanishTitle);
cmd.Parameters.AddWithValue("#SerieFrecuency", seriesInfo.frequency);
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
}
}
and the Error says:
errorCS0103: The name 'CommandText' does not exist in the current context. And when I use a watch I found out this: cmd.CommandText =""; . Can somebody tell me what im doing wrong please.?
So first of all. move cn.Close(); outside of the loops. If it's not the cause for your problem now, it will cause a problem later.
If that doesn't fix your problem look further.
It's just a poke in the dark given the information I have, but try running following code sets (inside foreach loop) and see if any of them work:
set 1:
cmd = new SqlCommand("INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency])
VALUES ('"+seriesInfo.seriesId+"', '"+seriesInfo.spanishTitle+"'
, '"+seriesInfo.frequency+"')", cn);
cmd.ExecuteNonQuery();
set 2:
cmd = new SqlCommand("INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency])
VALUES (#SerieID, #SerieName, #SerieFrecuency)", cn);
cmd.Parameters.AddWithValue("#SerieID", seriesInfo.seriesId);
cmd.Parameters.AddWithValue("#SerieName", seriesInfo.spanishTitle);
cmd.Parameters.AddWithValue("#SerieFrecuency", seriesInfo.frequency);
Let me know how it works out
Try this...
Modify the line below to include the name of the database. So that it will read [Your database Name].[dbo].[Serie]
cmd.CommandText = "INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency]) VALUES (#SerieID, #SerieName, #SerieFrecuency)";
Your default database may not be the one that has your "Serie" table in it.
On click button presents the following code,
For some reason it wont delete data from database, (the dropdownlist is valid) any advice or changes needed?
protected void deleteback_Click(object sender, EventArgs e)
{
// declare variables
String EditNewID = DropDownList3.SelectedItem.Value;
// set connection string to database
String connectionString = WebConfigurationManager.ConnectionStrings["ScrumString"].ConnectionString;
SqlConnection myConnection2 = new SqlConnection(connectionString);
// delete values to product backlog
myConnection2.Open();
String query = "DELETE * FROM product_backlog WHERE product_backlog.id = #id ";
SqlCommand commanddelete = new SqlCommand(query, myConnection2);
commanddelete.Parameters.AddWithValue("#id", EditNewID);
// refresh page
Page.Response.Redirect(Page.Request.Url.ToString(), true);
commanddelete.ExecuteNonQuery();
myConnection2.Close();
}
maybe you are creating one string ID instead an integer
Try something like
commanddelete.Parameters.Add("#id", SqlDbType.Int);
commanddelete.Parameters["#id"].Value = Int32.Parse(customerID);
I want to access value of a string outside the block of if(!Page.IsPostBack) in PageLoad.
I have declared string sap1 public.
My Code is
public partial class WebForm4 : System.Web.UI.Page
{
DateTime d = DateTime.Now;
string sap = "";
string sap1;
protected void Page_Load(object sender, EventArgs e)
{
//DateTime d = DateTime.Now;
TextBox1.Text = d.ToShortDateString();
if (!Page.IsPostBack)
{
string q = d.ToShortDateString();
string[] separators = { "-", "/" };
string s = d.ToShortDateString();
string[] words = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
sap = sap + word;
string constr = ConfigurationManager.ConnectionStrings["myString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
sap1 = "D" + sap;
string query = "create table " + sap1 + " (Name varchar(50),ContentType
nvarchar(200),Data varbinary(MAX));";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
AddNewRow();
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(sap1);
}
}
I want to access the value of sap1 outside the PageLoad. I want to use it for insert into Query.
You'll need to store the value of sap1 in a Session
Session["sap1"] = sap1;
Then retrieve it when you need it:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(Session["sap1"]);
}
You have to have some declaration of this property outside of the Page_Load method
private string sap1;
and then you can access it in whole class. But be careful about ASP.NET page life cycle. You will have sap1 with value only after Page_Load. In the earlier stages of the page life cycle it will be null of course.
The problem is the if check if(!Page.IsPostback). You need to calculate sap and sap1 on every PostBack. So it'll available when you click on the button.
Just remove the condition if(!Page.IsPostback).
I want to update this form's Login and Logout Time:
My code is :
protected void btnUpdate_Click(object sender, EventArgs e)
{
string LoginTime = txtIn.Text;
string LogOutTime = txtOut.Text;
long DayLogId = Convert.ToInt64(Request.QueryString["ID"]);
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =#"Data Source=DELL\SQLSERVER1;Initial Catalog=LoginSystem;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("UPDATE [DayLog] SET [LoginTime]=#LoginTime,[LogOutTime]=#LogOutTime WHERE [DayLogId]=#DayLogId");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#LoginTime", LoginTime);
dataCommand.Parameters.AddWithValue("#LogOutTime", LogOutTime);
dataCommand.Parameters.AddWithValue("#DayLogId", DayLogId);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
At the first two lines of method ,
string LoginTime = txtIn.Text;
string LogOutTime = txtOut.Text;
when I debug , it does not show the value that I reinserted. This code works if I mannually write
string LoginTime = "11:44:11";
string LogOutTime = "12:44:11";
NOTE:
The value of forms in text box is coming from another page GridView.
protected void grdEmployee_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
GridViewRow grRow = ((Control)e.CommandSource).NamingContainer as GridViewRow;
Label DayLogId = grRow.FindControl("lblDayLogId") as Label;
if (Convert.ToInt16(DayLogId.Text) > 0)
{
Response.Redirect("~/Employee/OutLog_Day.aspx?ID=" + DayLogId.Text, false);
}
}
}
You should make sure that the text box gets populated before the click event runs. As Steve suggested, usually you get this when you initialize the data on every postback which is unnecessary if the data is not changed.
Im pretty new to wf4 but have created a simple console app with submit, approve and reject capabilities just fine. Im now trying to create an asp.net app that consumes the service i have created but am getting a fault exception as shown below. This worked fine in my console app
The execution of an InstancePersistenceCommand was interrupted because
the instance key '3a552603-c92f-2424-085c-7b6fc1a0e98e' was not associated to
an instance
Basically ive created 3 simple pages. the first page is a simple form where the user submits a request. the 2nd page just prints a list of the requests. Clicking on one of the requests takes you to the 3rd page that prints a more detailed view of the request with an approve and decline button. Im using a GUID for the correlation which is passed to the 3rd page through the query string. Clicking the approve button fires the approve method of the service passing in the query string value. Its at this point i get the exception. The strange thing is the guid in the error message is not the same as the value im passing in.
Any ideas below is my code is that helps
1st page
protected void Unnamed1_Click(object sender, EventArgs e) {
ServiceReference1.ServiceClient Client = new ServiceReference1.ServiceClient();
ServiceReference1.Request R = new ServiceReference1.Request();
R.Title = TxtRequestTitle.Text;
R.Amount = Convert.ToInt32(TxtAmount.Text);
Guid g = Guid.NewGuid();
Client.SubmitRequest(R, g);
Response.Write("submitted");
}
2nd page
protected void Page_Load(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(#"Data Source=bantai11\sqlexpress;Initial Catalog=RequestMonkey;Integrated Security=True;Asynchronous Processing=True")) {
using (SqlCommand com = new SqlCommand()) {
com.Connection = con;
com.CommandType = System.Data.CommandType.Text;
com.CommandText = "Select InstanceId, Title, state from Requests";
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(com);
sda.Fill(dt);
rp.DataSource = dt;
rp.DataBind();
}
}
}
3rd page
protected void Page_Load(object sender, EventArgs e) {
this._id = Request.QueryString.Get("Id");
using (SqlConnection con = new SqlConnection(#"Data Source=bantai11\sqlexpress;Initial Catalog=RequestMonkey;Integrated Security=True;Asynchronous Processing=True")) {
using (SqlCommand com = new SqlCommand()) {
con.Open();
com.Connection = con;
com.CommandType = System.Data.CommandType.Text;
com.CommandText = "Select InstanceId, Title, state from Requests where instanceid = '" + this._id + "'";
SqlDataReader dr = com.ExecuteReader();
dr.Read();
lblTitle.Text = dr[1].ToString();
lblGuid.Text = dr[0].ToString();
lblAmount.Text = "0";
}
}
}
protected void btnApprove_Click(object sender, EventArgs e) {
ServiceReference1.ServiceClient Client = new ServiceReference1.ServiceClient();
Client.Approve(1, this._id);
}
The exception indicates that the InstanceStore couldn't find a workflow associated with that key. It could be that the workflow has already completed or aborted with an error. You need to get tracking data on the WorkflowService to see what is going wrong. See Troubleshooting Workflow Services with diagnostic logging