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.
Related
I have a page where n number of text boxes are created according the value n from a drop down list. My question is about accessing the values from the textboxes into string variables so that I can store them in database.
Following is the code for creating textboxes
protected void ddlNumOfVolunteers_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
// Get the number of labels to create.
int numlabels = System.Convert.ToInt32(ddlNumOfVolunteers.SelectedItem.Text);
for (int i = 1; i <= numlabels; i++)
{
Label myLabel = new Label();
TextBox txtbox = new TextBox();
// Set the label's Text and ID properties.
myLabel.ID = "LabelVol" + i.ToString();
myLabel.Text = "Volunteer " + i.ToString();
txtbox.ID = "TxtBoxVol" + i.ToString();
PlaceHolder1.Controls.Add(myLabel);
PlaceHolder2.Controls.Add(txtbox);
// Add a spacer in the form of an HTML <br /> element.
PlaceHolder2.Controls.Add(new LiteralControl("<br />"));
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
Then when I click on the save button beneath, I want to access all the values in the dynamically created textboxes and store into a datastructure such as array.
I used the following code and I know it won't work as TxtBoxVol1 won't be available in this block. so how can I store the values in an array when in ddlNumOfVolunteers_SelectedIndexChanged function itself.
protected void btnStart_Click(object sender, EventArgs e)
{
TextBox tb = (TextBox)this.FindControl("PlaceHolder2").FindControl("TxtBoxVol1");
string vol1name = tb.Text;
}
Thanks in advance
There are oodles of ways to do this.
However, you could just store them in an array of List<T> or even a Dictionary
Dictionary<string,Textbox> myControls = new Dictionary<string,Textbox>();
...
TextBox txtbox = new TextBox();
txtbox.Id = "TxtBoxVol" + i.ToString();
myControls.Add(txtbox.Id,txtbox)
...
var myValue = myControls["TxtBoxVol1"].Text
// when you are finished
myControls.Clear();
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;
}
I need your help in making text box at run time and taking values from these text boxes that user enter. i have two button and one rich_text_box , when user click on one button it creates 3 text boxes and then user click on other button it should take value from text boxes and how in rich text box .
this is code i am using to create dynamic textbox
private void create_textbox_Click(object sender, EventArgs e)
{
flowLayoutPanel1.Controls.Clear();
for(i=1;i<=3;i++)
{
TextBox text = new TextBox();
text.Name = "Text Box" + i.ToString();
//text.Text = "Text Box " + i.ToString();
flowLayoutPanel1.Controls.Add(text);
}
}
and this code i am using to take values from new created text boxes and displaying in rich text box .
private void get_value_Click(object sender, EventArgs e)
{
TextBox text = new TextBox();
for (i = 1; i <= 3; i++)
{
string value = text.Text + i.ToString();
richTextBox1.SelectedText = "\r\n" + value;
}
}
This should solve your problem:
private void get_value_Click(object sender, EventArgs e)
{
for (var c in flowLayoutPanel1.Controls)
{
var t = c as TextBox;
if (t != null)
{
richTextBox1.SelectedText = "\r\n" + t.Text;
}
}
}
In your method get_value_Click you aren't using any of the text boxes that were added to the flow layout panel. Something similar to Wolfgang Ziegler's answer should work but you will need to check the Type and Name in case you have other controls in the flow layout panel.
private void get_value_Click(object sender, EventArgs e)
{
for (i = 1; i <= 3; i++)
{
string value = this.flowLayoutPanel1.Controls["Text Box" + i].Text;
richTextBox1.SelectedText = "\r\n" + value;
}
}
This ought to do it.
I am trying to build an app, where user can select category and according to it displays its sub categories , these sub categories are buttons, which are dynamically created.
Now, as buttons are dynamically created so I am confuse how to write code under button_click event as I dont know how many subcategories are there.
So is there any way I can execute click event of a particular button , so that I can execute certain commands?
EDITED
This is the code that i tried
Button btnDynamicButton = new Button();
private void btnclick_Click(object sender, EventArgs e)
{
label2.Text = btnDynamicButton.Text;
}
private void btnappetizer_Click(object sender, EventArgs e)
{
groupBox2.Visible =false;
DataTable dt = new DataTable();
dt = itemmasterbl.SelectallrecordFromtblItem(btnappetizer.Text);
for (int i = 0; i < dt.Rows.Count; i++)
{
string name = "Appetizer" + DynamicButtonCount;
Button btnDynamicButton1 = new Button();
btnDynamicButton1.Name = name;
btnDynamicButton1.Text = name;
btnDynamicButton1.Size =
new System.Drawing.Size(150, 30);
btnDynamicButton1.Location =
new System.Drawing.Point(180, DynamicButtonCount * 30);
btnDynamicButton1.Click +=new EventHandler(btnclick_Click);<br>
Controls.Add(btnDynamicButton1);
DynamicButtonCount++;
btnDynamicButton = btnDynamicButton1;
}
}
Once I do this it creates three buttons according to number of values in itemmaster DB under appetizer, but once I click on any of the three buttons the label displays only last buttons text,because in last line I have :
btnDynamicButton = btnDynamicButton1;
Which will last buttons infos,but rather I want which ever button I press, label should display respective text. How can I achieve this.
you can put all your logic into one handler:
System.Windows.Forms.Button b = new System.Windows.Forms.Button();
b.Click += new EventHandler(b_Click);
//finally insert the button where it needs to be inserted.
...
void b_Click(object sender, EventArgs e)
{
MessageBox.Show(((System.Windows.Forms.Button)sender).Name + " clicked");
}
To your edit:
You are storing the reference for your button(s) inside the Field btnDynamicButton. Hence it always gets overwritten with the latest button you have created. You should not reference the button by using a field. The sender parameter of the click-handler contains the button element that has been clicked. See the code above: Simple cast sender to Button and you know which button has been clicked:
private void btnclick_Click(object sender, EventArgs e)
{
Button btn = (Button)sender
label2.Text = btn.Text;
}
Problem:
I have a value in a database table. This value can either contain a number, or null. If its null I would like to show one group of controls. If its not null I would like to show another group of controls.
Previous Attempts:
I have tried creating the controls in the code behind depending on the value of the database. This worked. However, on postback I get a null reference exception. The control doesn't exist on postback because the page is stateless. I'm building the controls in the page_load handler (depending on the value of the table column). Since I'm creating the controls in the page_load shouldn't they exist on postback?
I also tried recreating the controls in the event handler for the button. I get a "theres already a control with this id" exception (presumably because I already created it in the page_load method).
I read a few posts about how I have to store the controls in a session. This seems like more work than it should be.
Questions:
Am I going about this the wrong way? This seems like it should have been simple but is turning into a mess.
If this is the correct way to do this, Where do I add the session information? I've been reading other posts and I'm kind of lost
Code:
int bookId;
string empName;
protected void Page_Load(object sender, EventArgs e)
{
if(int.TryParse(Request.QueryString["id"], out bookId))
{
//This is where the value in the database comes into play. If its null Book.GetCopyOwner
// returns a string with length 0
empName = Book.GetCopyOwner(bookId, Request.QueryString["owner"]);
if (empName.Trim().Length > 0)
{
CreateReturnControls();
}
else
{
CreateCheckoutControls();
}
}
}
protected void ReturnButton_Click(object sender, EventArgs e)
{
}
protected void CheckOut_Click(object sender, EventArgs e)
{
int bookId;
if (int.TryParse(Request.QueryString["id"], out bookId))
{
TextBox userId = (TextBox)this.Page.FindControl("UserId");
//WHEN I TRY TO USE THE TEXTBOX userId HERE, I GET NULL REFERENCE EXCEPTION
BookCopyStatusNode.Controls.Clear();
CreateReturnControls();
}
}
protected void CopyUpdate_Click(object sender, EventArgs e)
{
}
private void CreateCheckoutControls()
{
TextBox userId = new TextBox();
//userId.Text = "Enter Employee Number";
//userId.Attributes.Add("onclick", "this.value=''; this.onclick=null");
userId.ID = "UserId";
Button checkOut = new Button();
checkOut.Text = "Check Out";
checkOut.Click += new EventHandler(CheckOut_Click);
TableCell firstCell = new TableCell();
firstCell.Controls.Add(userId);
TableCell secondCell = new TableCell();
secondCell.Controls.Add(checkOut);
BookCopyStatusNode.Controls.Add(firstCell);
BookCopyStatusNode.Controls.Add(secondCell);
}
private void CreateReturnControls()
{
Label userMessage = new Label();
userMessage.Text = empName + " has this book checked out.";
Button returnButton = new Button();
returnButton.Text = "Return it";
returnButton.Click += new EventHandler(ReturnButton_Click);
TableCell firstCell = new TableCell();
firstCell.Controls.Add(userMessage);
TableCell secondCell = new TableCell();
secondCell.Controls.Add(returnButton);
BookCopyStatusNode.Controls.Add(firstCell);
BookCopyStatusNode.Controls.Add(secondCell);
}
It looks like you're creating a static set of controls based on the database value. Why not simply have 2 Panels that contain the controls you want and simply set their visibility to true or false:
if (!Page.IsPostBack)
{
if (int.TryParse(Request.QueryString["id"], out bookId))
{
empName = Book.GetCopyOwner(bookId, Request.QueryString["owner"]);
var display = (empName.Trim().Length > 0);
panelReturnControls.Visible = display;
panelCheckoutControls.Visible = !display;
}
}