persistent text boxes in c# asp.net - c#

I fill the textboxes on page_load event.Then I edit textboxes data and tried to update data. Variables are assigned with old values. How can I do to get the new values.
Here is my code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class mymembertype : System.Web.UI.Page
{
public static int mem_typeid;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["valueid"] != null)
{
mem_typeid = (int)(Session["valueid"]);
string memtype_name = Convert.ToString(Session["valueName"]);
string rate = Convert.ToString(Session["rate"]);
txtmembtype.Text = Convert.ToString(memtype_name);
txtdscrate.Text = rate;
Insert_membertype.Text = "Update";
}
}
protected void Insert_membertype_Click(object sender, EventArgs e)
{
funtions fun = new funtions();
if (txtmembtype.Text != "" && txtdscrate.Text != "" )
{
if (Insert_membertype.Text == "Save")
{
string membetype = txtmembtype.Text;
int dscrate = Convert.ToInt32(txtdscrate.Text);
bool chk = fun.Insert_membertype(membetype, dscrate);
if (chk)
lblInfo.Text = " saving membertype successful";
else
lblInfo.Text = "Error saving membertype";
}
else
{
string membetype = txtmembtype.Text;
int dscrate = Convert.ToInt32(txtdscrate.Text);
bool chk = fun.Update_memberType(mem_typeid, membetype, dscrate);
if (chk)
lblInfo.Text = " Updating membertype successful";
else
lblInfo.Text = "Error Updating membertype";
}
}
}
}
As you see second condition block is for updating data. But it have only values in page load.Now new data is assigned. Please ....

Your problem is that Page Load is called before the event handler for your controls. If you want to understand more about the order things happen in ASP.net just Google "ASP.Net Page Lifecycle" - if you're going to be doing a lot of development I recommend at least getting a basic understanding of what ASP.Net is doing.
You'll want to change your page load to check if the current request is a postback.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && Session["valueid"] != null)
{
// Doing stuff
}
}
The "IsPostBack" variable is false the first time the page is loaded, and then is true for every subsequent load.

Try if(!IsPostBack) method in Pageload event

You need to write the code inside page_load under IsPostback condition like below to get the updated values
if (!IsPostBack)
{
// Bind your code here
}

write a code GetData Method.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData();
}
}
public void GetData()
{
}

Related

Issue with Session Variables

So I'm trying to make a simple banking website using C# and ASP.net and I'm just learning about Session Variables for the first time. I have a starting account balance of 1000 dollars and I want to transfer that to another page and have that balance updated via withdrawals or deposits and then update the balance. Heres my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Project4.Forms
{
public partial class Services : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click1(object sender, EventArgs e)
{
double userInput = double.Parse(txtAmount.Text);
Session["userInput"] = userInput;
Session["balance"] = 1000.00;
double balance = Convert.ToDouble(Session["balance"]);
Session["userAction"] = ddlSelectService.SelectedItem.Text;
if (ddlSelectService.SelectedItem.Text == "Withdrawl")
{
balance -= userInput;
}
else if (ddlSelectService.SelectedItem.Text == "Deposit")
{
balance += userInput;
}
else
{
}
Response.Redirect("Status.aspx");
}
}
}
I understand the root of my problem is probably the original Session["balance"] = 1000.00; but I'm not sure how to declare a starting amount and then it not affect the balance when I return to this page from the results page. Any help is appreciated, also as I said in the beginning this is a barebones simple atm website please don't suggest anything too crazy because I am a beginner.
I don't do asp.net, so this is just a guess, but maybe try only setting the default value if it's null, something like: if (Session["balance"] == null) Session["balance"] = 1000;. It also seems like this should be in the Page_Load event, not the btnSubmit_Click event, since it only has to happen once.
Finally, don't forget to update the session variable after setting the new balance:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["balance"] == null) Session["balance"] = 1000;
}
protected void btnSubmit_Click1(object sender, EventArgs e)
{
double userInput;
if (!double.TryParse(txtAmount.Text, out userInput))
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert",
"alert('Input must be a valid double');", true);
return;
}
Session["userInput"] = userInput;
double balance = Convert.ToDouble(Session["balance"]);
Session["userAction"] = ddlSelectService.SelectedItem.Text;
if (Session["userAction"] == "Withdrawl")
{
balance -= userInput;
}
else if (Session["userAction"] == "Deposit")
{
balance += userInput;
}
Session["balance"] = balance;
Response.Redirect("Status.aspx");
}

Change text in specific row in gridview using checkbox

I want to change a specific text in my gridview here's an image below:
Example if I click the checkbox button the specific row "Status" text is change to "Validated".
This is my aspx code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using MSSQLConnector;
namespace SoftwareAnalysisAndDesign.SAD
{
public partial class TeacherPage : System.Web.UI.Page
{
private MSConnector connector = new MSConnector();
private DataSet SubjectlistData;
private DataTable SubjectlistTable;
string query = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Populate The Select Tag with Subjects
SubjectList.DataSource = Session["TeacherSubjectList"];
SubjectList.DataTextField = "CourseNo";
SubjectList.DataValueField = "CourseNo";
SubjectList.DataBind();
}
}
}
protected void TeacherSubjects_Click(object sender, EventArgs e)
{
string getText = SubjectList.SelectedItem.Text;
//Connection String
connector.ConnectionString = "Data Source=keith;Initial Catalog=SAD;Integrated Security=True";
query = "select StudentID,CourseNo,CourseDescription,Units,Day,StartTime,EndTime,Room,Instructor,Amount,Status from assessmentform where CourseNo = '" + getText + "'";
SubjectlistData = connector.ExecuteQuery(query);
SubjectlistTable = SubjectlistData.Tables[0];
//Add a colum check row
SubjectlistTable.Columns.Add("Check", Type.GetType("System.Boolean"));
Session["ValidateSubject"] = SubjectlistTable;
Response.Redirect("ValidateSubjectTeacher.aspx");
}
I add a checkbox in my row to my gridview using this:
//Add a colum check row
SubjectlistTable.Columns.Add("Check", Type.GetType("System.Boolean"));
Session["ValidateSubject"] = SubjectlistTable;
I pass my gridview using session to another page,
its aspx code behind ValidatePage:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SoftwareAnalysisAndDesign.SAD
{
public partial class ValidateSubjectTeacher : System.Web.UI.Page
{
CheckBox check = new CheckBox();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ValidateSubject"] == null)
{
Response.Redirect("TeacherPage.aspx", true);
}
if (!IsPostBack)
{
ValidateSubject.DataSource = Session["ValidateSubject"];
ValidateSubject.DataBind();
}
//I add my checkbox in the last row using this
foreach (GridViewRow row in ValidateSubject.Rows)
{
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox;
check.Enabled = true;
}
}
protected void ValidateSubject_Click(object sender, EventArgs e)
{
if(check.Checked)
{
//This condition here is I want to change the Status when check to validated.
}
}
}
in my code behind using session I bind all the data in DataTable(FirstPage);
DataSet ds = connector.ExecuteQuery(query);
DataTable dt = dt.Table[0];
dt.DataBind();
Session["SubjectList"] = dt;
You can use the NamingContainer property like this:-
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk= (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give you row
grvRow.Cells[10].Text = "Validated"; //Updated the cell text in that row.
//Or if Status is a control like label then //
Label StatusLabel = (Label)grvRow.FindControl("StatusLabel");
StatusLabel.Text = "Validated";
}
Alternatively, you can also use the RowDataBound event.
Update:
Since you are binding the grid with directly i.e. AutoGenerateColumns set as true, you will have to attach the event handler of checkbox programmatically as well like this:-
//I add my checkbox in the last row using this
foreach (GridViewRow row in ValidateSubject.Rows)
{
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox;
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event
check.AutoPostBack = true; //Set the AutoPostBack property to true
}
Now, in your event first find the row with the help of checkbox, then update the Status column like this:-
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk= (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give you row
if(chk.Checked)
{
grvRow.Cells[10].Text = "Validated";
}
}
You can use an Extension Method like this:
public static class myExtensionsMethods
{
public static void validateRow(this object sender)
{
int columnIndex = 10;
GridViewRow myRow = ((Control)sender).Parent as GridViewRow;
myRow.Cells[columnIndex].Text = "Validated";
}
}
The extension method will allow you to call it in this way
protected void ValidateSubject_Click(object sender, EventArgs e)
{
if (check.Checked)
{
sender.validateRow();
}
}

Event not firing with dynamically placed user control asp.net c#

I’m trying to create a webpage that displays dynamically placed WebUserControls depending on a question type that is returned from and SQL server. When you press a button on the usercontrols it checks the result from the usercontrol using the procedure “CheckResult”. For some reason when you click on the buttons within the usercontrols ("cmdProcess") the Event “CheckResult” does not fire. What am I doing wrong please?
The User control code is: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Testing.Event_Delegate
{
public partial class WebUserControl2 : System.Web.UI.UserControl
{
// Delegate declaration
public delegate void PhotoUploaded(string strFilename, String FailureMessage, string strFabricationNo, string strPartNo, string strBatchNo, string strPartSN, string strSTK_SerialNo, string strSTK_PartNo);
// Event declaration
public event PhotoUploaded Resultresponse;
string questionAsked;
public string QuestionText
{
set { questionAsked = value; }
get { return questionAsked; }
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = QuestionText;
TextBox1.Focus();
}
protected void cmdProcess_Click(object sender, EventArgs e)
{
if (Resultresponse != null)
{
Resultresponse("Passed", "", "", "", "", "", "", "");
}
TextBox1.Text = "";
}
}
}
And the main ASPX page that the usercontrols are placed on is: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Testing.Event_Delegate
{
public partial class WebForm1 : System.Web.UI.Page
{
WebUserControl2 QT2;
WebUserControl3 QT3;
DataTable dtQuestionSet;
protected void Page_Load(object sender, EventArgs e)
{
// all controls need to be rendered every page postback otherwise the rest of the code loses scope.
QT2 = (WebUserControl2)this.LoadControl("WebUserControl2.ascx");
QT3 = (WebUserControl3)this.LoadControl("WebUserControl3.ascx");
if (IsPostBack == false)
{
Session["Counter"] = 0;
Session["QuestionCount"] = 0;
Session["CompletedInsp"] = false;
Session["RunInsp"] = false;
dtQuestionSet = new DataTable();
MakeDataTabledtQuestionSet();
}
else
{
dtQuestionSet = (DataTable)Session["DataTableW"];
//check to see if the inspection process is complete and display pass\fail and log. Else carry on.
if (Convert.ToBoolean(Session["CompletedInsp"]) == true)
{
//Response.Write("Failed");
ModalPopupExtender2.Show();
return;
}
}
Session["DataTableW"] = dtQuestionSet;
}
void CheckResult(string Result, string FailureMessage, string FabricationNo, string PartNo, string BatchNo, string PartSN, string STK_SerialNo, string STK_PartNo)
{
Label1.Text = "You Answered: - " + Result;
if ((Convert.ToInt32(Session["Counter"]))>= Convert.ToInt32(Session["QuestionCount"]))
{
Session["CompletedInsp"] = true;
Session["RunInsp"] = false;
}
else
{
dtQuestionSet = (DataTable)Session["DataTableW"];
}
Session["Counter"] = Convert.ToInt32(Session["Counter"]) + 1;
//If the inspection hasn't been completed carry on and ask next question.
if (Convert.ToBoolean(Session["RunInsp"]) == true)
{
RunInspection();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm1.aspx");
}
protected void cmdStartInspection_Click(object sender, EventArgs e)
{
Session["Counter"] = 0;
GetQuestions();
}
protected void GetQuestions()
{
dtQuestionSet.Clear();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PromptedInspConnectionString"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("test.GetQuestions", conn);
SqlDataReader dr = null;
cmd.CommandType = CommandType.StoredProcedure;
dr = cmd.ExecuteReader();
while (dr.Read())
{
DataRow drQuestions = dtQuestionSet.NewRow();
drQuestions["QuestionText"] = dr[1].ToString();
drQuestions["ExpectedResponse"] = dr[2].ToString();
drQuestions["QuestionType"] = dr[3].ToString();
dtQuestionSet.Rows.Add(drQuestions);
}
Session["DataTableW"] = dtQuestionSet;
Session["QuestionCount"] = dtQuestionSet.Rows.Count;
conn.Close();
RunInspection();
Session["RunInsp"] = true;
}
protected void RunInspection()
{
//Populate the user controls
switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
{
case "1":
QT2.QuestionText = dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][0].ToString();
QT2.Resultresponse += new WebUserControl2.PhotoUploaded(CheckResult);
break;
case "2":
QT3.QuestionText = dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][0].ToString();
QT3.Resultresponse += new WebUserControl3.PhotoUploaded(CheckResult);
break;
}
//Add the usercontrols to the form
PlaceHolder2.Controls.Add(QT2);
PlaceHolder2.Controls.Add(QT3);
//Need to set the visability of the usercontrol so it only shows the usercontrol that is displaying the question
QT2.Visible = false;
QT3.Visible = false;
switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
{
case "1":
QT2.Visible = true;
break;
case "2":
QT3.Visible = true;
break;
}
}
private void MakeDataTabledtQuestionSet()
{
dtQuestionSet.Columns.Add("QuestionText");
dtQuestionSet.Columns.Add("ExpectedResponse");
dtQuestionSet.Columns.Add("QuestionType");
}
}
}
Try initializing the controls in OnPreInit rather than load. Controls binding is done in OnPreInit.
See the page lifecyle events MSDN Reference

computation after choosing on a dropdownlist

I'm creating a simple patients billing program using Asp.net c#. Now, I have a dropdownlist with items "Ward" , "Semi Private" and "Private" If the user would choose ward the textbox below it would automatically be 700, if Semi Private it should be 1000 and if Private it should be 2000. I also have a textbox under it indicating how many days the patient stayed, the user is the one who should input the days, and for example he's from the ward room and the days he stayed was 3 then the computation should be 700 * 3. I also have a textbox that will display the answer. I hope u guys understand the things I explained above. So far, here are my codes:
Default.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.Text == "Ward")
{
TextBox4.Text = "700";
}
if (DropDownList1.Text == "Semi Private")
{
TextBox4.Text = "1000";
}
if (DropDownList1.Text == "Private")
{
TextBox4.Text = "2000";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
First of all add an attribute in your asp tag for dropdownlist like-
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
Then in the event, write the following code-
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.ToString();
if(selected == "Ward")
{
int NetAmount = 700 * 3; //you can use any int variable in place of "3" as well
TextBox1.Text = NetAmount.ToString();
}
else if(selected == "Semi Ward")
{
TextBox1.Text = "1000";
}
else
{
TextBox1.Text = "2000"
}
}
That's it. Hope it will help.

response.redirect doesnt work

When control reaches response.redirect line then the following error is produced in browser.
the url in response.redirect is correct.
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
* This problem can sometimes be caused by disabling or refusing to accept
cookies.
here is the code
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void imgbtnLogin_Click(object sender, ImageClickEventArgs e)
{
UserFunction objUser = new UserFunction();
UserProperties objUserProperties = new UserProperties();
IUserFunction iUserFunction = (IUserFunction)objUser;
objUserProperties.UserName = txtUserName.Text;
objUserProperties.Password = txtPassword.Text;
string userName = txtUserName.Text; ;
string password = txtPassword.Text; ;
DateTime login = DateTime.Now;
DateTime? logout = null;
int UserId;
string StartUpPage;
bool success = iUserFunction.ValidateUser(objUserProperties, out StartUpPage);
if (success)
{
Session["UserId"] = objUserProperties.UserId;
Session["RoleId"] = objUserProperties.RoleId;
Session["UserName"] = objUserProperties.UserName;
Session["MyTheme"] = objUserProperties.Theme;
iUserFunction.AddLoginHistory(objUserProperties.UserId, login, logout, 1);
Response.Redirect(StartUpPage);
}
else
{
Label1.Text = "Wrong UserName/password.";
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ClientScript", "alert('Invalid Credential');", true);
}
}
}
Could it be that you are redirecting to an endless loop? Here is a link to some info for that error.
If you had code like below for the two pages this could happen.
Page1.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect(Page2Url);
}
Page2.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect(Page1Url);
}
UPDATE
If you are positive it's not an infinite loop in your code I would follow the steps in this link and see if the issues is caused by cookies.
You are redirecting to the same page, causing an infinite loop.

Categories

Resources