I need enter manually some values during a loop for. I'm using C# ASP.Net with WebForms.
I'm trying this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace systemII
{
public partial class MY_System : System.Web.UI.Page
{
private List<String> List = new List<string>();
private bool loop = false;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
while (loop) { }
for (int i = 1; i <= 10; i++)
{
string a = "A" + i.ToString();
if (i == 4 || i == 5)
{
loop = true;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
else
{
List.Add(a);
}
}
}
protected void Button2_Click(object sender, EventArgs e) // modal button
{
string b = "BB";
Lista.Add(b);
loop = false;
return;
}
}
}
But the Modal appear on screen after end of loop. I need pause the loop until I enter the textbox value.
Any can help me? Sorry for my bad english.
In ASP.Net you cannot just pause the server-side code since the server-side code is always executed fully (never partially) even if you use asynchronous page in ASP.Net and also, server-side is never connected to browser but is executed in a separate process. Browser never knows and doesn't care what's happening on server-side, and the server-side doesn't know nor cares about what browser is doing, so it's impossible to connect server-side code to browser the way you want.
However, you can simulate what you want by breaking from the loop when the first index =4 is reached and modal popup script emitted. Then you can do a similar thing for i= 5 when user has inputted values for i=4 and page has posted back. But, the values of i that were successfully handled for input will need to be tracked across requests from browser, which is done in code below by setting a ViewState variable called HandledValues which is just a collection of List of string type.
So the workflow if you use this code will be: User will be prompted to input values for i=4 in a modal popup and then when a button Button1 is clicked and page posts back, the user will be prompted to input values for i = 5 in a modal popup.
protected void Button1_Click(object sender, EventArgs e)
{
//a list of values handled is stored in ViewState as ValuesHandled
List<string> handledValues = new List<string>();
if (ViewState["ValuesHandled"] != null) {
List<string> handledValues = (ViewState["ValuesHandled"] as List<string>;
}
for (int i = 1; i <= 10; i++)
{
string a = "A" + i.ToString();
//check if i = 4 has had its values input successfully
if (i == 4 && !handledValues.Contains(i.ToString()))
{
loop = true;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
handledValues.Add(i.toString());
//break the loop since we need to return to browser for input by user
break;
}
else if (i == 4 && handledValues.Contains(i.ToString()))
{
//remove handled value if no modal popup needed to be opened
handledValues.Remove(i.ToString())
}
else if (i == 5 && !handledValues.Contains(i.ToString()))
{//check if i = 5 has had its values input successfully
loop = true;
handledValues.Add(i.toString());
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
//break the loop since we need to return to browser for input by user
break;
}
else if (i == 5 && handledValues.Contains(i.ToString()))
{
//remove handled value if no modal popup needed to be opened
handledValues.Remove(i.ToString())
}
else
{
List.Add(a);
}
}
//update the ViewState for ValuesHandled
ViewState["ValuesHandled"] = handledValues;
}
Related
I have cookies and viewstate in below control .
This ajax Control is used to upload multiple file images.
protected void OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
int userid = 25;
DAL_Cart objdalcart = new DAL_Cart();
if (Viewstate["Imagestringname"] == null)
{
objdalcart.InsertTempImage(userid, ImageName, 1);
}
else
{
objdalcart.InsertTempImage(userid, ImageName, 0);
}
Response.Cookies["JewelleryUserCookiesUserId"].Value = Convert.ToString(userid);
Response.Cookies["JewelleryUserCookiesUserId"].Expires = DateTime.Now.AddYears(1);
Viewstate["Imagestringname"] = ImageName + ",";
}
The issue is when I try to retrive view state value or Cookies value on different click event of button in same page I am not able to retrive the value
protected void lnkcheckout_Click(object sender, EventArgs e)
{
if (Request.Cookies["JewelleryUserCookiesUserId"] == null || Request.Cookies["JewelleryUserCookiesUserId"].Value == "")
{
}
if (Viewstate["Imagestringname"] != null)
{}
}
For both the case it is going in if condition. for viewstate I have placed Enableviewstate=true on master page .Any idea why?
Review
Want ajax multiple file upload on my button click event
var c = new HttpCookie("JewelleryUserCookiesUserId");
c.Value = Convert.ToString(userid);
c.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(c);
Just note: this is insecure. the client can manipualte the cookie...
I'm trying to create a simple login screen, which has 2 textboxes and 1 button. When strings i've insterted in the first textbox (username) and the second textbox (password) matches the strings i've defined before, the buttons Enabled propertie should become True and when clicked, it should open another form, here's the code i've written so far:
public partial class LogInScreen : Form
{
public LogInScreen()
{
InitializeComponent();
string lietotajvards = "user";
string parole = "user";
if (textBox1.Text == lietotajvards && textBox2.Text == parole)
{
button1.Enabled = true;
}
else
{
button1.Enabled = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
this.Hide();
f1.Show();
}
}
The thing is that with my code it doesn't work as expected and the button is enabled all the time. Where's the problem?
Your code will only execute once when the form is initialized, you have to make use of a textchanged event on textbox1 and textbox2, thereafter you can use the code you wrote to check if the button needs to be enabled. In the else you must disable the button.
Text changed event handlers:
void textBox1_TextChanged(object sender, EventArgs e)
{
handleLoginButton();
}
void textBox2_TextChanged(object sender, EventArgs e)
{
handleLoginButton();
}
Enable/disable button:
private void handleLoginButton(){
string lietotajvards = "user";
string parole = "user";
if (textBox1.Text == lietotajvards && textBox2.Text == parole)
{
button1.Enabled = true;
}
else
{
button1.Enabled = false;
}
}
The constructor only runs once for the form, you need to handle the text changed events for the input controls and then re-evaluate your condition again.
Also it should go without saying (although it is being said here) that this is a terrible way to handle logging in to an application.
I'm brand new to the subject and very lost. I have a text box on my webSite. The data entered into the textBox will be placed in an array, and a counter will increase. Once the counter reaches five, you cannot add more to the array.
There will be a button to display all the names input into the array, which clears the array and the counter as well.
I have no idea how to order classes and methods in C#. I put the buttons inside of the main class so that I can share variables between them, but then I can't access the text box.
Some code is there because I'm trying to figure this out, but it may not belong in here. The code is also rather bare because I'm just trying to figure it all out. Any help is appreciated.
<script runat="server">
public partial class Arrays
{
private int Counter = 0;
protected void btnEnter_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
btn.Text = (Int32.Parse(btn.Text) + 1).ToString();
Label1.Text = "Enter Another student's name";
}
public void btnEnter_Click2(object sender, EventArgs e)
{
Label1.Text = "Enter a student's name ";
}
}
</script>
First you need to focus how you keep the previous data on the page.
From Post to Post you can store them ether on ViewState ether on a control.
As I see there is save the previous state on the btn.Text, that is not so cool, but ok accepted.
protected void btnEnter_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
// the btn.Text keeps the number of post backs (enters of name).
var Counter = Int32.Parse(btn.Text);
Counter++;
if(Counter >= 5)
{
Label1.Text = "No more studen's names please";
}
else
{
btn.Text = Counter.ToString();
Label1.Text = "Enter Another student's name";
}
}
As you see is "store" the counter in the btn.Text an use this to know know many post have been done.
Some way like that you can use to store the entered names. I prefer to save it on viewstate and I can do that with this code.
const string cArrNameConst = "cArr_cnst";
public string[] cArrKeepNames
{
get
{
if (!(ViewState[cArrNameConst] is string[]))
{
// need to fix the memory and added to viewstate
ViewState[cArrNameConst] = new string[5];
}
return (string[])ViewState[cArrNameConst];
}
}
and with that code you can add from 0->4 any name on cArrKeepNames[] on your code and have it after the post back, because is keep it on viewstate of the page.
protected void btnEnter_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
var Counter = Int32.Parse(btn.Text);
// here you save the name in the array
// an magically is saved inside the page on viewstates data
// and you can have it anywhere on code behind.
cArrKeepNames[Counter] = NameFromEditor.Text;
Counter++;
if(Counter >= 5)
{
btn.Enable = false;
Label1.Text = "No more studen's names please";
}
else
{
btn.Text = Counter.ToString();
Label1.Text = "Enter Another student's name";
}
}
a simple code like that can read the array at any time:
foreach (var One in cArrKeepNames)
txtOutput.Text += "<br>" + One;
I test it and is working good.
i have a confirm and alert message box.
both are getting displayed at the right time.
but in confirm box when i press cancel the applyaction_button_click is getting executed, which should not happen as i return false.
Similar is the case with alert box which returns false still applyaction_button_click is getting executed.
here is my code:
protected void Page_Load(object sender, EventArgs e)
{
ApplyAction_Button.Attributes.Add("onclick", "ShowConfirm();");
}
protected void ApplyAction_Button_Click(object sender, EventArgs e)
{
// Action to be applied
}
JS function:
function ShowConfirm() {
//check if checkbox is checked if is checked then display confirm message else display alert message
var frm = document.forms['aspnetForm'];
var flag = false;
for (var i = 0; i < document.forms[0].length; i++) {
if (document.forms[0].elements[i].id.indexOf('Select_CheckBox') != -1) {
if (document.forms[0].elements[i].checked) {
flag = true
}
}
}
if (flag == true) {
if (confirm("Are you sure you want to proceed?") == true) {
return true;
}
else {
return false;
}
} else {
alert('Please select at least Checkbox.')
return false;
}
}
thanks
When you have a client side event on an asp server control that has a server event and both get triggered with the same action, returning true or false on the client doesn't stop it from executing its server event.
You could try to prevent the button's server event from executing by doing some kind of postback in your javascript code.
In my page when I call searchBtn_Click the selectedvalue will be carried into the variable ind only if the selection hasnt changed. So if a User selects Automotive, then clicks the search button, and then they change the selection to Government, it will refresh the page and display Automotive, am I missing something in the postback or doing something wrong here?
protected void Page_Load(object sender, EventArgs e)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
protected void searchBtn_Click(object sender, EventArgs e)
{
string ind = IndustryDropDownList.SelectedValue;
Response.Redirect("Default.aspx?ind=" + ind);
}
Simply replace your code with this code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
}
You don't need to use Redirect and QueryString.
Use SelectedValue at Page_PreRender (In your sample clear Page_Load completely).
you better try this in search button click
but remember your dropdowndlist's value-member==display-member to do this.. i had the same problem and this is how i solved it.
string ind = IndustryDropDownList.Text.Tostring().Trim();
Response.Redirect("Default.aspx?ind=" + ind);
i knw this is not the best way but it did work for me..
You're not leveraging the ViewState of asp.net forms (good mentality for MVC 3 though). But since you are using asp.net, you should change your code to this:
The logic in your page load is not necessary, unless you want the user to set the industry as the enter the page. Since I assumed you do, I left some logic in there. It checks for postback because it doesn't need to execute after the initial page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack() && Request.QueryString["ind"] != null)
{
SetIndustry(Request.QueryString["ind"].ToString());
}
}
protected void SetIndustry(String industry)
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
You don't have to redirect the page, since Page_Load will be called every time the page posts back. With .NET, your controls remember their last values automatically.
protected void searchBtn_Click(object sender, EventArgs e)
{
SetIndustry(IndustryDropDownList.SelectedValue);
}