Setting Session Variables when image buttons are clicked? - c#

I have two image buttons on the page. When either is clicked it needs to set the session variables yesID and NoId before the page is posted back. I tried putting the code in the click events for each button but the page loads again before it runs that code in the click events. How can i set the 2 session variables when either image is clicked?
<div id="MainPics">
<div id="RightPic">
<p>
<asp:Label ID="FirstPicMemberNameLabel" runat="server" Text="" Font-Bold="True" ForeColor="White"></asp:Label>
</p>
<asp:ImageButton ID="FirstPicLink" Width="90%" runat="server"
onclick="FirstPicLink_Click" />
</div>
<div id="LeftPic">
<p>
<asp:Label ID="SecondPicMemberNameLabel" runat="server" Text="" ForeColor="White" Font-Bold="True"></asp:Label>
</p>
<asp:ImageButton ID="SecondPicLink" Width="90%" runat="server"
onclick="SecondPicLink_Click" />
</div>
<div id="skip">
<asp:LinkButton ID="LBNoChoice" PostBackUrl="~/default.aspx" ForeColor="White" runat="server">Skip - I Can't Choose</asp:LinkButton>
</div>
</div>
Code Behind Page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["yesID"] = 0;
Session["noId"] = 0;
}
else
{
//Send Session Variables to Database for Storage.
}
}
protected void FirstPicLink_Click(object sender, ImageClickEventArgs e)
{
Session["yesID"] = 1;
Session["noId"] = 2;
}
protected void SecondPicLink_Click(object sender, ImageClickEventArgs e)
{
Session["yesID"] =2;
Session["noId"] = 1;
}

Does this logic help?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["yesID"] = 0;
Session["noId"] = 0;
}
//else
//{
//Send Session Variables to Database for Storage.
//}
}
protected void FirstPicLink_Click(object sender, ImageClickEventArgs e)
{
Session["yesID"] = 1;
Session["noId"] = 2;
SendSessionVariables(Session["yesID"], Session["noId"]);
}
private void SendSessionVariables(object p, object p_2)
{
// Your database code here
}
protected void SecondPicLink_Click(object sender, ImageClickEventArgs e)
{
Session["yesID"] = 2;
Session["noId"] = 1;
SendSessionVariables(Session["yesID"], Session["noId"]);
}

When you click on the asp.net image button, It usually fires the click event and calls the method if autopostback is not disabled. If you really want to change the session values before the autopostback being hit, Invoke a client side javascript function on the onclientclick event and from that, make an ajax call to a server page where you update the session variable values. Once you get the response from the ajax call (success event) , return true so that the web page continues with the form post back event.

Related

Checking if the value of a textbox is changed or not

I have a textbox filled at the page load. I want to check the value of the textbox is changed or not in the "update" button press. Any solution? TIA.
Well, you could say use client side javascript.
But, you could also do this:
Say this text box:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Done - continue" OnClick="Button1_Click" />
And our code could be this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// code here to setup and load controls
TextBox1.Text = "Dog";
ViewState["TextBox1"] = "Dog";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != (string)ViewState["TextBox1"])
{
// then text box was changed
}
}

ASP.net textbox with range textmode keeps resetting it's value

Hi i am busy creating a asp.net project that needs to get three values from the user. I am using a textbox with a range textmode to get these values and the first time the user moves the slider it works perfectly but after that the user can.t adjust any of the textboxes anymore.
I tried using a slider extender but this does not seem to work and only a textbox shows.
my html code to create the textboxes and labels showing the value
body>
<form id="form1" runat="server">
<p>
Quantum 1 Length:
<asp:TextBox ID="txtVal1" runat="server" TextMode="Range" min="1" Max="8" OnTextChanged="txtVal1_TextChanged1" AutoPostBack="True"></asp:TextBox>
<asp:Label ID="lblVal1" runat="server" Text="/////"></asp:Label>
</p>
<p>
Quantum 2 Length:
<asp:TextBox ID="txtVal2" runat="server" TextMode="Range" min="1" Max="8" OnTextChanged="txtVal2_TextChanged1" AutoPostBack="True"></asp:TextBox>
<asp:Label ID="lblVal2" runat="server" Text="/////"></asp:Label>
</p>
<p>
Quantum 3 Length:
<asp:TextBox ID="txtVal3" runat="server" TextMode="Range" min="1" Max="8" AutoPostBack="True" OnTextChanged="txtVal3_TextChanged1"></asp:TextBox>
<asp:Label ID="lblVal3" runat="server" Text="/////"></asp:Label>
</p>
<p>
<asp:Button ID="btnNext" runat="server" AutoPostBack="true" Height="24px" OnClick="btnNext_Click" style="margin-left: 0px" Text="Next" Width="150px" />
<script type="text/javascript" __designer:mapid="129">
function NextPage() {
window.open('Execution.aspx', 'Execution');
}
</script>
<asp:Label ID="lblError" runat="server" ForeColor="Red" Text="Invalid input; Please ensure that Quantum 1 <= Quantum 2 <= Quantum 3" Visible="False"></asp:Label>
</p>
</form>
</body>
My C# code used to control the boxes and change their values
public partial class Quantums : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
txtVal1.Text = HttpContext.Current.Session["Q1"].ToString();
}
catch { }
try
{
txtVal2.Text = HttpContext.Current.Session["Q2"].ToString();
}
catch { }
try
{
txtVal3.Text = HttpContext.Current.Session["Q3"].ToString();
}
catch { }
lblVal1.Text = txtVal1.Text;
lblVal2.Text = txtVal2.Text;
lblVal3.Text = txtVal3.Text;
//UpdatePanel1.Triggers.Add(new AsyncPostBackTrigger() { ControlID = "btnNext" });
}
protected void txtVal1_TextChanged1(object sender, EventArgs e)
{
HttpContext.Current.Session["Q1"] = txtVal1.Text;
}
And then the same code for textbox 2 and 3. Any suggestions on why the textboxes vaklue keeps resetting and autopostback is enabled on all three buttons.
I just noticed you were missing if(Page.IsPostBack()) return;. Your problem is that every time you change your textbox, the 'Page_Load' event is enacted, then the respective event handler (see page life cycle). So you were setting the text to the sessions, then setting the sessions to the text, effectively doing nothing.
You actually don't need anything for this page in the Page_load method, at least for now. Try the following:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void txtVal1_TextChanged(object sender, EventArgs e)
{
Session["Q1"] = txtVal1.Text;
lblVal1.Text = txtVal1.Text;
}
protected void txtVal2_TextChanged(object sender, EventArgs e)
{
Session["Q2"] = txtVal2.Text;
lblVal2.Text = txtVal2.Text;
}
protected void txtVal3_TextChanged(object sender, EventArgs e)
{
Session["Q3"] = txtVal3.Text;
lblVal3.Text = txtVal2.Text;
}
You can then access the user input values using the respective session values. For example:
protected void Submit(object sender, EventArgs e)
{
List<string> answers = new List<string>();
answers.Add(Session["Q1"].ToString());
answers.Add(Session["Q2"].ToString());
answers.Add(Session["Q3"].ToString());
// Do stuff with answers
}

ASP.NET - SelectedValue/Index in Listbox always changing after a postback

I've been wrestling with this problem for days and so far I haven't been able to find an answer that fits this specific issue. Here's the code to load the list in the PageLoad():
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
lstEmprendimientos.DataSource = Emprendimiento.DevolverEmprendimientosConEvaluacionesIncompletas();
lstEmprendimientos.DataValueField = "id";
lstEmprendimientos.DataTextField = "titulo";
lstEmprendimientos.DataBind();
pnlEvaluador.Visible = false;
}
}
The first method loads a list made up of 'Emprendimiento' objects, and on that list's SelectedIndexChanged I call another method to load a list through a method that uses the SelectedValue of the item selected.
My problem is that, no matter what I do, the SelectedIndex is always reset to 0 after a postback, so I can't load the second list using the SelectedValue properly. I've worked with lists for a long while now and I've never had this problem, so it's really baffling. I'd appreciate some help with this.
Here's the code for the whole page:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ddlEmprendimientos.DataSource = Emprendimiento.DevolverEmprendimientosConEvaluacionesIncompletas();
ddlEmprendimientos.DataValueField = "id";
ddlEmprendimientos.DataTextField = "titulo";
ddlEmprendimientos.DataBind();
pnlEvaluador.Visible = false;
}
}
protected void lstEmprendimientos_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void lstEvaluadores_SelectedIndexChanged(object sender, EventArgs e)
{
Evaluador ev = Evaluador.FindByID(lstEvaluadores.SelectedValue);
}
protected void btnAsignarEvaluador_Click(object sender, EventArgs e)
{
Emprendimiento emp = Emprendimiento.FindByID(Convert.ToInt32(ddlEmprendimientos.SelectedValue));
Evaluador ev = Evaluador.FindByID(lstEvaluadores.SelectedValue);
Evaluacion eva = new Evaluacion(emp, ev, 0, "justificacion", DateTime.Now, false);
if (eva != null)
{
if (eva.Insertar())
{
lblFeedback.Text = "Alta exitosa.";
emp.listaEvaluaciones.Add(eva);
lstEvaluadores.DataSource = emp.DevolverListaEvaluadoresQueNoEvaluanEmprendimiento();
lstEvaluadores.DataTextField = "Nombre";
lstEvaluadores.DataValueField = "Email";
lstEvaluadores.DataBind();
pnlEvaluador.Visible = true;
CargarEvaluadores();
}
else
{
lblFeedback.Text = "Error en el ingreso de datos.";
}
}
else
{
lblFeedback.Text = "Error en el ingreso de datos.";
}
}
protected void btnSeleccionarEmp_Click(object sender, EventArgs e)
{
CargarEvaluadores();
}
private void CargarEvaluadores()
{
Emprendimiento emp = Emprendimiento.FindByID(Convert.ToInt32(ddlEmprendimientos.SelectedIndex));
lstEvaluadores.DataSource = emp.DevolverListaEvaluadoresQueNoEvaluanEmprendimiento();
lstEvaluadores.DataTextField = "Nombre";
lstEvaluadores.DataValueField = "Email";
lstEvaluadores.DataBind();
pnlEvaluador.Visible = true;
}
protected void ddlEmprendimientos_SelectedIndexChanged(object sender, EventArgs e)
{
CargarEvaluadores();
}
Page markup:
<%Page Title="" Language="C#" MasterPageFile="~/masterPage.Master" AutoEventWireup="true" CodeBehind="asignarEvaluador.aspx.cs" Inherits="InterfazUsuario.asignarEvaluador">
<asp:DropDownList ID="ddlEmprendimientos" runat="server" OnSelectedIndexChanged="ddlEmprendimientos_SelectedIndexChanged">
</asp:DropDownList>
<br />
<br />
<asp:Button ID="btnSeleccionarEmp" runat="server" OnClick="btnSeleccionarEmp_Click" Text="Seleccionar emprendimiento" Width="195px" />
<br />
<br />
<asp:Panel ID="pnlEvaluador" runat="server">
<asp:ListBox ID="lstEvaluadores" runat="server" OnSelectedIndexChanged="lstEvaluadores_SelectedIndexChanged"></asp:ListBox>
<br />
<br />
<asp:Button ID="btnAsignarEvaluador" runat="server" OnClick="btnAsignarEvaluador_Click" Text="Asignar evaluador" Width="135px" />
<br />
<br />
<asp:Label ID="lblFeedback" runat="server"></asp:Label>
<br />
</asp:Panel>
You need to change your DropDownList and ListBox controls to AutoPostback
DropDownList
<asp:DropDownList ID="ddlEmprendimientos" runat="server"
OnSelectedIndexChanged="ddlEmprendimientos_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
ListBox
<asp:ListBox ID="lstEvaluadores" runat="server"
OnSelectedIndexChanged="lstEvaluadores_SelectedIndexChanged"
AutoPostBack="True">
</asp:ListBox>
AutoPostBack:
Set this property to true if the server needs to capture the selection
as soon as it is made. For example, other controls on the Web page can
be automatically filled depending on the user's selection from a list
control.
This property can be used to allow automatic population of other controls on > the Web page based on a user's selection from a list.
The value of this property is stored in view state.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.autopostback(v=vs.110).aspx
I found the problem after checking everything out again.
The DataValueField in the list was 'id', and the id field in the 'Emprendimiento' class wasn't defined, so it was always returning a null int (0). Thank you kindly for the help, it was just a dumb mistake in the end.

persist ddl values and selected value in between postbacks

I have a save button and a drop down list on a page. Inside the page Load, the drop down list is populated if !Page.PostBack (AutoPostBack=false). So, the first time I load the page, the drop down list is populated. I also have a save method to go with the save button. When this button is clicked, it should do something with the selected value of the drop down list. My problem is that the drop down list has no value (is null) inside the button save method. How would you fix this?
Markup:
MyClass.aspx
<%# Page Language="C#" AutoEventWireup="true" Inherits="MyClass" %>
<asp:Content ID="Content3" ContentPlaceHolderID="MainRegion" runat="server">
<div>
<asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="myDdlChange" ViewStateMode="Enabled" EnableViewState="true" />
</div>
<br />
<div style="min-width: 300px; max-width: 770px;">
<asp:TextBox id="txtBox" runat="server" TextMode="MultiLine" />
</div>
<div class="buttonContainer">
<span >
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
</span>
</div>
</asp:Content>
Then, in the code behind:
MyClass.aspx.cs
public class MyClass
{
protected global::System.Web.UI.WebControls.DropDownList myDdl;
protected global::System.Web.UI.WebControls.TextBox txtBox;
protected global::System.Web.UI.WebControls.Button btnSave;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (this.Page.IsPostBack)
Session["selectedID"] = myDdl.SelectedValue; // my attempt to put the selected value from ddl in a session var, to use it later inside the save method but it didn't work
if (!Page.IsPostBack)
{
//create array1 here
myDdl.Items.Clear();
myDdl.Items.AddRange(array1);
Session["selectedID"] = myDdl.SelectedValue;
myDdlChange(null, null);
this.DataBind();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
//do something based on myDdl.SelectedValue (which shouldn't be null)
}
protected void myDdlChange(object source, EventArgs e)
{
txtBox.Text = myDdl.SelectedValue;
}
}
}
I think the main problem is you should be using Page_Load instead of OnLoad.
You don't need to use Session to remember the SelectedValue.
Try something like this which works for me...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
PopulateDropdown();
}
private void PopulateDropdown()
{
myDdl.Items.Clear();
var array1 = new ListItem[3];
array1[0] = new ListItem("item1", "item1");
array1[1] = new ListItem("item2", "item2");
array1[2] = new ListItem("item3", "item3");
myDdl.Items.AddRange(array1);
myDdl.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
var selectedVal = myDdl.SelectedValue; // putting a breakpoint here shows myDdl.SelectedValue is not null
}
protected void myDdlChange(object sender, EventArgs e)
{
}

How to I carried out Textbox value from ViewState when I postback?

I want to know that how can I trace out the value of Textbox from ViewState.
As user enters any value into Textbox and click submit button because of postback Textbox value disappears ,
But if I used ViewState in this case , then is there any way to see or display that value from Viewstate?
<html>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /
</form>
</body>
</html>
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text += "X";
}
In your page load use this.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (ViewState["Values"] == null)
{
ViewState["Values"] = new string();
}
}
TextBox1.Text = ViewState["Values"].ToString();
}
After that use this.
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["Values"] += TextBox1.Text;
}
In the first Page_Load method, You will create a ViewState if its not a postback and its null. After that write the textbox your viewstate, in Button1_Click you will add your new textbox1 to your viewstate.

Categories