Input string never equals the random string - c#

It should return "success", but it always returns the answer of "fail".
protected void Button3_Click(object sender, EventArgs e)
{
Random rnd = new Random();
randomNumber = (rnd.Next(100000, 999999)).ToString();
Label1.Text = randomNumber;
}
protected void Button2_Click(object sender, EventArgs e)
{
if (TextBox1.Text != randomNumber)
{
Label1.Text = "fail";
}
else
{
Label1.Text = "success";
}
}
Here is the HTML part.
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
<asp:Button ID="Button3" runat="server" Text="Button" OnClick="Button3_Click" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Your randomNumber is a class-level field. Its value will not be persisted between requests.
If you want to persist the value between requests, then you need to store it in the ViewState:
private string RandomValue
{
get { return (string)ViewState["RandomValue"]; }
set { ViewState["RandomValue"] = value; }
}
protected void Button3_Click(object sender, EventArgs e)
{
Random rnd = new Random();
RandomNumber = (rnd.Next(100000, 999999)).ToString();
Label1.Text = RandomNumber;
}
protected void Button2_Click(object sender, EventArgs e)
{
if (TextBox1.Text != RandomNumber)
{
Label1.Text = "fail";
}
else
{
Label1.Text = "success";
}
}
ASP.NET Page Life Cycle Overview

Related

Set focus in texbox at last char in an asp.net web page using c#

I have a textbox in an asp.net web page. In case of postback, I need to set focus on last char in this texbox. how can I do this using c# without using anything like jQueries..
Thanks
Here is a variation of the solution proposed in Use JavaScript to place cursor at end of text in text input element:
void btnPostBack_Click(object sender, EventArgs e)
{
txtFocus.Attributes["onfocus"] = "var value = this.value; this.value = ''; this.value = value; onfocus = null;";
txtFocus.Focus();
}
Your code like below :
asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" ontextchanged="TextBox1_TextChanged" TabIndex="1">
asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True" ontextchanged="TextBox2_TextChanged" TabIndex="2">
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Session["event_controle"] = ((TextBox)sender);
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
Session["event_controle"] = ((TextBox)sender);
}
protected void Page_PreRender(object sender, EventArgs e)
{
try
{
if (Session["event_controle"] != null)
{
TextBox controle =(TextBox) Session["event_controle"];
controle.Focus();
}
}
catch ()
{
}
}

Gridview Get Cells ID

I want to select gridview to get the ID. My code is below. What can I do to achieve this?
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int id = Convert.ToInt32(GridView1.SelectedRow.Cells[0].ToString());
TextBox2.Text = id.ToString();
}
Check this , it may work for u ,Call cell id directly.
this.GridView1.CellClick += new System.Windows.Forms.GridViewCellEventHandler(this.GridView1_CellClick);
private void GridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
string id = GridView1.Rows[GridView1.CurrentRow.Index].Cells["ID"].Value.ToString();
textBox1.Text = id;
}
catch (Exception)
{
}
}
or change this in ur code..
string id = GridView1.Rows[GridView1.CurrentRow.Index].Cells[0].Value.ToString();
textBox1.Text = id;
Add this...
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chksec" runat="server" AutoPostBack="True" oncheckedchanged="chksec_CheckedChanged1" />
</ItemTemplate>
</asp:TemplateField>
protected void chksec_CheckedChanged1(object sender, EventArgs e)
{
Response.Write("Checkbox is checked");
}

Limit consecutive numbers entered into textbox [Calculator App]

I am building a calculator app (it is homework, full disclosure) and have got myself into a bit of a jam. One of the requirements is "make sure that you will not be able to enter more than 9 digits. (i.e., < 1,000,000,000)".
What I'd really like to do is cap off an entered number to 9 digits and make exceptions for operators (+ - * /)
Things I've tried>
Using RegularExpressionValidator and while I am able to use that to limit the text but it is less than ideal.
Creating an integer to use as a counter in the code-behind, and have each input that is a digit increase the counter by 1 and each operator reset it to 0. Then, when any digit key is pressed, have it check to see if the Counter >=9 and have it display an alert if so. That was what I was really hoping would work but I had no luck.
My solve method requires that the entire expression (including operators) be in the CurrentInput textbox. If I'm not able to figure this out, I'm going to have to scrap what I'm doing and do it another way. That'd be unfortunate, because I've also built an identical calculator using Javascript and I'd have to re-do that as well. My goof was not thinking through the intended behavior of the calculator before I got this far. From the requirements (linked below), it seems the display boxes only show numbers and keep the current operator in a separate box. I have the current operator displayed as well to the right of the "9" key but also in the display box.
Requirements
This is my design, and i've pasted screenshots next to each other to demonstrate its behavior in one continuous operation. 450 divided by 150 = 3 then if an operator is the next entered input, it continues to modify the result so: * 200 + 550 = 1150. If a digit is the next entered input, it sends the result to the top display so: 5 * 5 = 25. I don't really know exactly how a dual display calculator is supposed to work but that's the best I can figure.
Design&Behavior
This is my ASP.Net code:
<body>
<form id="CAsp" runat="server">
<div>
<asp:Table ID="Table1" runat="server">
<asp:TableHeaderRow runat="server">
<asp:TableHeaderCell CssClass="th" ColumnSpan="4" runat="server" Enabled="false">
<asp:TextBox ID="Result" runat="server"></asp:TextBox>
</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableHeaderRow runat="server">
<asp:TableHeaderCell CssClass="th" ColumnSpan="4" runat="server" Enabled="false">
<asp:TextBox ID="CurrentInput" runat="server"></asp:TextBox>
</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow CssClass="toprow" runat="server">
<asp:TableCell CssClass="topleft" runat="server">
<asp:Button ID="Seven" CssClass="smallbutton" runat="server" OnClick="Seven_OnClick" Text="7" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Eight" CssClass="smallbutton" runat="server" OnClick="Eight_OnClick" Text="8" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Nine" CssClass="smallbutton" runat="server" OnClick="Nine_OnClick" Text="9" /></asp:TableCell>
<asp:TableCell CssClass="topright" runat="server">
<asp:Button ID="OP" CssClass="OP" runat="server" Enabled="false" Text="" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server">
<asp:TableCell runat="server">
<asp:Button ID="Four" CssClass="smallbutton" runat="server" OnClick="Four_OnClick" Text="4" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Five" CssClass="smallbutton" runat="server" OnClick="Five_OnClick" Text="5" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Six" CssClass="smallbutton" runat="server" OnClick="Six_OnClick" Text="6" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Clear" CssClass="smallbutton" runat="server" OnClick="Clear_OnClick" Text="C" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server">
<asp:TableCell runat="server">
<asp:Button ID="One" CssClass="smallbutton" runat="server" OnClick="One_OnClick" Text="1" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Two" CssClass="smallbutton" runat="server" OnClick="Two_OnClick" Text="2" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Three" CssClass="smallbutton" runat="server" OnClick="Three_OnClick" Text="3" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Divide" CssClass="smallbutton" runat="server" OnClick="Divide_OnClick" Text="/" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server">
<asp:TableCell runat="server">
<asp:Button ID="Zero" CssClass="smallbutton" runat="server" OnClick="Zero_OnClick" Text="0" /></asp:TableCell>
<asp:TableCell CssClass="topright" runat="server">
<asp:Button ID="Plus" CssClass="smallbutton" runat="server" OnClick="Plus_OnClick" Text="+" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Minus" CssClass="smallbutton" runat="server" OnClick="Minus_OnClick" Text="-" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Multiply" CssClass="smallbutton" runat="server" OnClick="Multiply_OnClick" Text="*" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow CssClass="bottomrow" runat="server">
<asp:TableCell CssClass="bottomcell" ColumnSpan="4" runat="server">
<asp:Button ID="Equals" CssClass="longbutton" runat="server" OnClick="Equals_OnClick" Text="=" /></asp:TableCell>
</asp:TableRow>
</asp:Table>
<div align="center">
<asp:RegularExpressionValidator ID="REV1" runat="server" ForeColor="red" ErrorMessage="Max Characters is 9, Use Backspace" ControlToValidate="CurrentInput" Display="Dynamic" ValidationExpression="^[0-9+-/*\s]{0,9}$" /></div>
</div>
</form>
And this is my C# code-behind:
public partial class CalcAsp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Equals_OnClick(object sender, EventArgs e)
{
try
{
string Input = CurrentInput.Text;
DataTable datatable = new DataTable();
Object result;
result = datatable.Compute(Input, null);
CurrentInput.Text = result.ToString();
OP.Text = "=";
}
catch
{
CurrentInput.Text = "Error";
}
}
protected void Clear_OnClick(object sender, EventArgs e)
{
CurrentInput.Text = "";
Result.Text = "";
OP.Text = "";
}
protected void Plus_OnClick(object sender, EventArgs e)
{
if (CurrentInput.Text == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", "alert('Enter A Digit!');", true);
}
else
{
CurrentInput.Text = CurrentInput.Text + "+";
OP.Text = "+";
}
}
protected void Minus_OnClick(object sender, EventArgs e)
{
if (CurrentInput.Text == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", "alert('Enter A Digit!');", true);
}
else
{
CurrentInput.Text = CurrentInput.Text + "-";
OP.Text = "-";
}
}
protected void Multiply_OnClick(object sender, EventArgs e)
{
if (CurrentInput.Text == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", "alert('Enter A Digit!');", true);
}
else
{
CurrentInput.Text = CurrentInput.Text + "*";
OP.Text = "*";
}
}
protected void Divide_OnClick(object sender, EventArgs e)
{
if (CurrentInput.Text == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", "alert('Enter A Digit!');", true);
}
else
{
CurrentInput.Text = CurrentInput.Text + "/";
OP.Text = "/";
}
}
public void Zero_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "0";
}
else
{
CurrentInput.Text = CurrentInput.Text + "0";
}
}
public void One_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "1";
}
else
{
CurrentInput.Text = CurrentInput.Text + "1";
}
}
public void Two_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "2";
}
else
{
CurrentInput.Text = CurrentInput.Text + "2";
}
}
protected void Three_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "3";
}
else
{
CurrentInput.Text = CurrentInput.Text + "3";
}
}
protected void Four_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "4";
}
else
{
CurrentInput.Text = CurrentInput.Text + "4";
}
}
protected void Five_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "5";
}
else
{
CurrentInput.Text = CurrentInput.Text + "5";
}
}
protected void Six_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "6";
}
else
{
CurrentInput.Text = CurrentInput.Text + "6";
}
}
protected void Seven_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "7";
}
else
{
CurrentInput.Text = CurrentInput.Text + "7";
}
}
protected void Eight_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "8";
}
else
{
CurrentInput.Text = CurrentInput.Text + "8";
}
}
protected void Nine_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "9";
}
else
{
CurrentInput.Text = CurrentInput.Text + "9";
}
}
protected void backSpace_Click(object sender, EventArgs e)
{
String str = CurrentInput.Text;
int len;
len = str.Length;
CurrentInput.Text = "";
for (int i = 0; i < len - 1; i++)
{
CurrentInput.Text = CurrentInput.Text + Convert.ToString(str[i]);
}
}
}
Thanks for any pointers. I've been reading stackoverflow for years so I think I'm coming in within the community norms on this question, but it is my first post. :)
You can use MaskedEdit Validator from AjaxControlToolkit. It sets pre-defined format for your textbox and prevents user from entering anything other than that. I used this control in one of my project and it works like a charm. The behaviour of the control is rendered in javascript at runtime and it makes a smooth user experience without any postback to server.
For more details - http://www.ajaxcontroltoolkit.com/MaskedEdit/MaskedEdit.aspx
Let me know if you need further help.
First, I would create a method to handle the number clicks. Then alter your insertion code to include a counter of some sort. Something like this might work:
protected void InsertNumber(int number)
{
int numberCount = 0;
for (int i = 0; i < CurrentInput.Text.Length; i++)
{
try
{
if (Enumberable.Range(0, 9).Contains(Convert.ToInt32(CurrentInput.Text.Substring(i, 1))))
{
numberCount++;
}
}
catch
{
// Do nothing?
}
}
if (numberCount <= 9)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = number.ToString();
}
else
{
CurrentInput.Text += number.ToString();
}
}
}
// Exacmple usage, apply to all buttons
protected void Nine_OnClick(object sender, EventArgs e)
{
InsertNumber(9);
}
I cannot test at the moment, but it should work.

how to assign value for drop down select item c#

i need to assign value for selected value drop down in aspx for example
dropdownlist items
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
<asp:ListItem>c</asp:ListItem>
</asp:DropDownList>
if user select any item in dropdownlist1 it should increment value 2 then
if user select any item in dropdownlist2 it should increment value 2
i need to display total
i tried this code
static int i = 0;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
i += 2;
Label1.Text = "hello"+i;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
i += 2;
Label1.Text = "hello"+i;
}
its working but problem is if user first select 1 in dropdown //i=2 then user select b //i=4 if user again select 1 //i=6. it should not increment if user select any value in particular drop down list. how to do it. any idea....
You're using a static variable so the i value will be kept between postbacks and will be common to all users, this is incorrect.
You need to store it in ViewState, HiddenField, or Session in order to keep the value between postbacks and also keep the value different for each user.
Here's what I would've done using ViewState:
private int Counter
{
get
{
if (ViewState["Counter"] == null)
{
return 0;
}
else
{
return (int)ViewState["Counter"];
}
}
set
{
ViewState["Counter"] = value;
}
}
private bool DropDown1Selected
{
get
{
if (ViewState["DropDown1Selected"] == null)
{
return false;
}
else
{
return (bool)ViewState["DropDown1Selected"];
}
}
set
{
ViewState["DropDown1Selected"] = value;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!this.DropDown1Selected)
{
this.DropDown1Selected = true;
this.Counter += 2;
}
Label1.Text = string.Format("hello{0}", this.Counter);
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
this.Counter += 2;
Label1.Text = string.Format("hello{0}", this.Counter);
}
Few of the answers above are talking about static variable getting reset after post back, this is incorrect, Static variables keep their values for the duration of the application domain. It will survive many browser sessions until you restart the web server Asp.net Static Variable Life time Across Refresh and PostBack
That being said, it is definitely not a good idea to use Static variables and instead go with the approaches suggested using Session or Viewstate.
About your question, I guess you want to increment the value only first time a value is chosen from the drop down list, to achieve this you would want to have a flag to let you know if the value is already selected, something on the below lines:
static bool DrpDown1;
static bool DrpDown2;
static int i = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DrpDown1 = false;
DrpDown2 = false;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DrpDown1)
{
i += 2;
Label1.Text = "hello" + i;
DrpDown1 = true;
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DrpDown2)
{
i += 2;
Label1.Text = "hello" + i;
DrpDown2 = true;
}
}
You need a temporary store like ViewState or Session to keep you values and get it back from
there.
private int GetValue()
{
return Int32.Parse(ViewState["temp"]);
}
private void SetValue(int i)
{
if(ViewState["temp"]==null)
{
ViewState["temp"]=i;
}
else
{
ViewState["temp"]= i+Int32.Parse(ViewState["temp"]);
}
}
and use it in your code as follows
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SetValue(2);
Label1.Text = string.Format("hello{0}", GetValue());
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
SetValue(2);
Label1.Text = string.Format("hello{0}", GetValue());
}

ASP.Net Checkbox in C#

Ok so I am getting into programing in ASP.Net with C#. I am trying a very simple procedure but it is very buggy. So I have the following ASP code:
<asp:Button ID="Button1" runat="server" Text="Show Numbers" onclick="Button1_Click1" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server"
oncheckedchanged="CheckBox1_CheckedChanged" />
I then have the following C# code behind it:
int i = 0;
List<int> Chosen = new List<int>();
public void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click1(object sender, EventArgs e)
{
if (i == 0)
{
TextBox1.Text = "Nothing here!";
}
else if (i == 1)
{
TextBox1.Text = Chosen[0].ToString();
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
Chosen.Add(1);
i++;
CheckBox1.Checked = true;
}
else if (CheckBox1.Checked == false)
{
Chosen.Remove(1);
i--;
CheckBox1.Checked = false;
}
}
The goal of the code is to have a checkbox on the screen. If it is checked I want to add the number 1 to my list (Chosen) also, when I push the button I want the textbox to display the number 1. If the checkbox becomes unchecked I want the number to get removed from the list and when I push the button I want it to display "Nothing here!".
The problem is, sometimes it works and sometimes it doesn't. For example if I click the box then the button it works. Then when I click the button again it says "Nothing Here!" it should stay as a 1.
You have to set AutoPostBack=true to the CheckBox control markup and also save that list into Session dictinary.
List<int> Chosen;
public void Page_Load(object sender, EventArgs e)
{
if(Sesstion["Chosen"]==null)
{
Session["Chosen"]=new List<int>();
}
Chosen = (List<int>)Session["Chosen"];
}

Categories

Resources