I have a array which I wan't to fill with a textbox, like the javascript .push() method.
Here is my code so far:
namespace Assigment9
{
public partial class Default : System.Web.UI.Page
{
double[] numbers = new double[5];
protected void Page_Load(object sender, EventArgs e)
{
}
protected void addButton_Click(object sender, EventArgs e)
{
double number = Convert.ToDouble(numberTB.Text);
}
}
You need to add the numbers to the array of numbers you declared
double[] numbers = new double[5];
Right now you are just declaring a new variable in addButton_Click called number and not doing anything with it.
It might be easier to use a list of numbers. I.E
List<double> numbers = new List<double>();
Then in addButton_Click just add the number
numbers.Add(mynumber);
You have declared an array of length 5 in the class this means you will need to declare an index variable and do bounds checking to make sure after the addButton is click that the array isnt full. I.E once the user clicks the button more than 5 times. Using the list avoids that effort.
Also you will have an exception in the addButton_Click handler if the user types in a non number value into the text box. You should also look to change that to something like double.TryParse.
public partial class Default : System.Web.UI.Page
{
public List<double> numbers
{
get
{
var list = ViewState["mylist"];
if (list == null) ViewState["mylist"] = new List<double>();
return ViewState["mylist"] as List<double>;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void addButton_Click(object sender, EventArgs e)
{
string value;
double number;
value = numberTB.Text;
if (Double.TryParse(value, out number)) numbers.Add(number);
// you should display some sort of message if the value isnt a number...
}
}
Since this is asp.net web forms you also need to stick the member variable in ViewState or Session otherwise the list or array / whatever will always be empty as web forms doesn't automatically persist member variable values for you.
I would go like this:
public partial class Default : System.Web.UI.Page
{
Collection<double> numbers = new Collection<double>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void addButton_Click(object sender, EventArgs e)
{
try
{
double number = Convert.ToDouble(numberTB.Text);
numbers.Add(number);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}' to a Double.", number);
}
catch (OverflowException) {
Console.WriteLine("'{0}' is outside the range of a Double.", number);
}
}
}
I know there are lots of way to get the same output .it is also one of them.
According to Your Comment
I know, but I want to be able to add something to numbers[0] and the second time i click the button it should add a number to numbers[1] etc
Here is Solution
namespace Assigment9
{
public partial class Default : System.Web.UI.Page
{
double[] numbers = new double[5];
int counter=0; // declare a global variable which will count the number of button clicks
protected void Page_Load(object sender, EventArgs e)
{
}
protected void addButton_Click(object sender, EventArgs e)
{
if(counter <5)
{
numbers[counter] = Convert.ToDouble(numberTB.Text);
counter ++;
}
}
}
Why would you like to use C# to load List from server side TextBox component. I would recommend to use Javascript for that.
But, if you explicitilly want to load list from c# code with TextBox you should use Session for instance because when you click on the button the page is making post back so the initialized list gets reseted.
Here's the result code:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
List<double> numbers = new List<double>();
Session["numbers"] = numbers;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["numbers"] != null)
{
List<double> numbersResult = Session["numbers"] as List<double>;
double number = Convert.ToDouble(TextBox1.Text);
numbersResult.Add(number);
Session["numbers"] = numbersResult;
}
}
Related
Goal: Keep value of int (professorIndex) reachable when I get to the button click method (btnUpdateAvailability_Click())
Problem: The value gets set correctly initially, then somehow goes to 0
What ive tried: Starting variable at class level. Getting rid of any other references to it, including commenting out where it was set to 0
What am I missing?
C#:
public partial class SiteMaster : MasterPage
{
private int professorIndex;
protected void Page_Load(object sender, EventArgs e) {
//some stuff
}
protected void cbUpdateAvailability_Click(object sender, EventArgs e)
{
CheckBox cbSender = (CheckBox)sender;
professorIndex = getProfessorIndexCB(cbSender.ClientID);
//at this point, professorIndex is 1, which is what I want/expect
}
public int getProviderIndexCB(string cbSender)
{
//professorIndex = 0;
switch (cbSender)
{
case "chkOnOff1":
professorIndex = 0;
break;
case "chkOnOff2":
professorIndex = 1; //This is the one that is triggered
break;
}
return professorIndex;
}
protected void btnUpdateAvailability_Click(object sender, EventArgs e)
{
//at this point, professorIndex is 0, no clue why. It should be one
}
Below a simple demo to store a value you want to persist in a Session and get it back on PostBack.
public int professorIndex = 0;
protected void Page_Load(object sender, EventArgs e)
{
//check for postback
if (!IsPostBack)
{
//set the index
professorIndex = 10;
//store the index in a session
Session["professorIndex"] = professorIndex;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//check if the session exists
if (Session["professorIndex"] != null)
{
//cast the session back to an int
professorIndex = (int)Session["professorIndex"];
}
//show result
Label1.Text = $"The professor index is {professorIndex}.";
}
What do I have to put in the private void textbox to make a user enter a amount and that amount will be applied to where await Connection.SendToServerAsync(2700, 790); is now. so let's say a user enters 2000, 8 in the texbox, then the (2700,790) has to change to (2000, 8)
namespace Application
{
public partial class Form1 : ExtensionForm
{
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
int repeat = 5;
for (int i = 0; i <= repeat; i++)
{
await Connection.SendToServerAsync(2700, 790);
await Connection.SendToServerAsync(3745);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
You can get the textbox value using TextBox.Text.
It comes as a string, so you have to convert to int. You can do that using one of the following:
Int.Parse
Convert.ToInt32
With the converted value you can just call the methods with the new values when the button is clicked.
I am using Asp.net(C#), and SQL Server. In web application I want 5 digit Invoice number in text box, and after clicking on button the gridviews data to be saved in database, and then invoice number in the text box should be increment by one...and so on. I used this code =>
protected void Page_Load(object sender, EventArgs e)
{
double ID = 00001;
txtinvoiceno.Text = Convert.ToString(ID);
and
protected void btnsavef1_Click(object sender, EventArgs e)
{
ID++;
var no = Convert.ToInt32(ID);
txtinvoiceno.Text = Convert.ToString(no);
}
but it shows in the output only single digit 1, and increment it only once time i.e.2, and further increment is not working.
Anyone have any idea on this??
Thanks & Regards,
I doubt this will even compile, as within btnsavef1_Click the variable ID is not defined. You probably want ID to be an instance-variable:
class MyClass {
private int ID = 0;
protected void Page_Load(object sender, EventArgs e)
{
txtinvoiceno.Text = this.ID.ToString("D5");
}
protected void btnsavef1_Click(object sender, EventArgs e)
{
this.ID++;
txtinvoiceno.Text = this.ID.ToString("D5");
}
}
Furthermore you won´t actually store the formatted number. Simply store the number as integer and do the formatting within your events-code using ToString and format-specifiers.
Try this :
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
int ID = 1;
txtinvoiceno.Text = ID.ToString("D5");
}
}
protected void btnsavef1_Click(object sender, EventArgs e)
{
int ID = Convert.ToInt16(txtinvoiceno.Text );
ID++;
txtinvoiceno.Text = ID.ToString("D5");
}
}
You´re looking for formatting, which is very easy in your case:
//DONE: int, not double - do you want to deal with round-up errors?
//DONE: ID should be a field, not a local variable
private int ID = 0;
protected void Page_Load(object sender, EventArgs e)
{
// whenever you want 5 digits - just put 5 zeroes when formatting
txtinvoiceno.Text = ID.ToString("00000");
...
}
protected void btnsavef1_Click(object sender, EventArgs e)
{
ID += 1;
// once again: want 5 digits - put 5 zeroes when formatting
txtinvoiceno.Text = ID.ToString("00000");
}
A better choice, IMHO, is to convert ID into property and hide formatting there:
private int m_ID;
public int ID {
get {
return m_ID;
}
set {
m_ID = value;
txtinvoiceno.Text = m_ID.ToString("00000");
}
}
...
protected void Page_Load(object sender, EventArgs e) {
// Just assign
ID = 0;
...
}
protected void btnsavef1_Click(object sender, EventArgs e) {
// Just increment
ID += 1;
}
Try this :
public partial class Form2 : Form
{
private double ID=0;
public Form2()
{
InitializeComponent();
}
protected void Page_Load(object sender, EventArgs e)
{
double ID = 00001;
txtinvoiceno.Text = Strings.Format(ID, "000000")
}
protected void btnsavef1_Click(object sender, EventArgs e)
{
ID++;
var no = Convert.ToInt32(ID);
txtinvoiceno.Text = Strings.Format(no, "000000")
}
}
you need to format only result number after increment.
protected void btnsavef1_Click(object sender, EventArgs e)
{
ID++;
var no = Convert.ToInt32(ID);
txtinvoiceno.Text = no.ToString().PadLeft(5, '0');
}
if ID=7
your result will be after Increment
will be 00008
I am trying to create a notepad like application in C# by using a Textbox.
I want to implement find function in it. I want an ability to search the text entered in textbox of Find form in textbox of Form1 and then highlight it.
Please help i am unable to do it
Form1.cs
private void findToolStripMenuItem_Click(object sender, EventArgs e)
{
Find f = new Find();
f.Show();
}
public void find()
{
int idx = 0;
while((idx=textBox1.Text.IndexOf(text))!=1)
{
textBox1.Select();//Select the text which are found
}
}
Find.cs
public partial class Find : Form
{
Form1 f = new Form1();
public Find()
{
InitializeComponent();
}
private void Cancelbutton2_Click(object sender, EventArgs e)
{
this.Close();
}
private void Findbutton1_Click(object sender, EventArgs e)
{
f.text =textBox1.Text;
f.find();
}
You need to specify the start and length parameter in the "Select" method. For Example:
textBox1.Select(idx, text.Length);
You can only highlight one section of data at a time with the standard TextBox. Try FastColourTextbox if you want better support.
private void textBox1_Enter(object sender, System.EventArgs e){
if (!String.IsNullOrEmpty(textBox1.Text))
{
textBox1.SelectionStart = 0;
textBox1.SelectionLength = textBox1.Text.Length;
}
}
I have a disabled text box thats' value only increments by one once a button is clicked, the problem is that it goes from 1 to 2 and thats it. I want it to increment everytime i push the button.
namespace StudentSurveySystem
{
public partial class AddQuestions : System.Web.UI.Page
{
int num = 1;
protected void Page_Load(object sender, EventArgs e)
{
QnoTextBox.Text = num.ToString();
}
protected void ASPxButton1_Click(object sender, EventArgs e)
{
num += 1;
QnoTextBox.Text = num.ToString();
}
}
}
Postback intializes the variable num to 1 again and you do not get the expected increamented result, you better you textbox value and store the value in ViewState.
protected void ASPxButton1_Click(object sender, EventArgs e)
{
num = int.Parse(QnoTextBox.Text);
num++;
QnoTextBox.Text = num.ToString();
}
Using ViewState
public partial class AddQuestions : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
ViewState["Num"] = "1";
}
protected void ASPxButton1_Click(object sender, EventArgs e)
{
QnoTextBox.Text = ViewState["Num"].ToString();
int num = int.Parse(ViewState["Num"].ToString());
ViewState["Num"] = num++;
}
}