String to Textbox - c#

I have created a method that allows me to find the next empty Box:
public int CheckBox(int boxNum) {
int BoxNumber = 0;
TextBox[] itemBoxArray = new TextBox[] { itemBox0, itemBox1, itemBox2, itemBox3, itemBox4, itemBox5, itemBox6, itemBox7,
itemBox8, itemBox9,itemBox10,itemBox11,itemBox12,itemBox13,itemBox14,itemBox15,};
for (int i = 0; i < itemBoxArray.Length; i++)
{
if (String.IsNullOrEmpty(itemBoxArray[i].Text))
{
BoxNumber = i;
i = 15;
}
}
return BoxNumber;
}
Next i created a button to check what the empty box is and i would like to input something into this box but i cannot find a way ro convert the string that carries the empty box number to that text box:
private void StandAroundRebar_Click(object sender, EventArgs e)
{
int emptybox = CheckBox(0);
string emptyboxString = emptybox.ToString();
string newbox = "itemBox" + emptyboxString;
MessageBox.Show("TextBox # " + newbox + " is empty ");
var textbox = this.Controls.Find(newbox, true);
}
}
}

Well, I would rather change the CheckBox method
public TextBox CheckBox() {
var itemBoxArray = new TextBox[] { itemBox0, itemBox1, itemBox2, itemBox3, itemBox4, itemBox5, itemBox6, itemBox7,
itemBox8, itemBox9,itemBox10,itemBox11,itemBox12,itemBox13,itemBox14,itemBox15,};
return itemBoxArray.First(m => string.IsNullOrEmpty(m.Text));//or FirstOrDefault
}
now you would get a TextBox returned, and could do whatever you want with it.

You need this function:
http://msdn.microsoft.com/de-de/library/486wc64h(v=vs.110).aspx
This will find it, all you have to do is casting it.
Then:
BoxNumber = i;
i = 15;
What should that do? You set the i to the box number and then you set it again to 15?!
That isn't supposed to work.

Why not just return the TextBox object directly?
public TextBox GetNextEmptyTextBox()
{
return (new[] { textBox1, textBox2, textBox3 })
.FirstOrDefault(tb => string.IsNullOrEmpty(tb.Text));
}

You need Control.ControlCollection.Find and than a cast to TextBox.
TextBox newBox = this.Controls.Find("itemBox1", true).FirstOrDefault() as TextBox;
Once you find your Box you can set the text:
newBox.Text = "my text";

Related

How can I find the sum of the elements within a ListBox in WPF

How can I find the sum of the elements within a ListBox. I just need to find a way to store the sum of the values of the ListBox and output once the users inserts the wrong input
private void theMethod(object sender, RoutedEventArgs e)
{
// YesButton Clicked! Let's hide our InputBox and handle the input text.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
// Do something with the Input
String input = InputTextBox.Text;
int result = 0;
if (int.TryParse(input, out result))
{
MyListBox.Items.Add(result); // Add Input to our ListBox.
}
else {
String[]arr = new String[3];
// I just want to be able to output the sum of the elements of the ListBox (MyListBox)
for ( i = 0; i < MyListBox.Items.Count; i++)
{
//MyListBox.Items[i].ToString();
MyListBox.Items.Cast<ListBoxItem>().Sum(x => Convert.ToInt32(x)).ToString();
}
sum.ToString();
MessageBox.Show("Sum is: " +MyListBox.Items.Cast<ListBoxItem>().Sum(x => Convert.ToInt32(x)).ToString());
}
The problem of your code is here:
MyListBox.Items.Cast<ListBoxItem>
To calculate sum of items of your list box, if you are sure that they are integer numbers that added as int or string, you can use this snippet:
var sum= this.ListBox1.Items.Cast<object>()
.Select(x => Convert.ToInt32(x))
.Sum();
MessageBox.Show(sum.ToString());
The above code assumes that you add items to ListBox using such code:
var value= this.TextBox1.text;
//your logic for null checking and ...
this.ListBox1.Items.Add(value);
Here is the complete code that I test based on your codes.
While you are adding integer values to listbox, we don't need Cast<object> and Select(x=>Convert.ToInt32(x)) anymore and its enough to Cast<int> like below:
String input = InputTextBox.Text;
int result = 0;
if (int.TryParse(input, out result))
{
MyListBox.Items.Add(result);
}
else
{
var sum = this.MyListBox.Items.Cast<int>().Sum();
MessageBox.Show(string.Format("Sum is: {0}", sum));
sum.ToString();
}
InputTextBox.Text = String.Empty;
this worked for me , try this :
private void YesButton_Click(object sender, RoutedEventArgs e)
{
int sum = 0;
int i = 0;
// YesButton Clicked! Let's hide our InputBox and handle the input text.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
// Do something with the Input
String input = InputTextBox.Text;
int result = 0;
if (int.TryParse(input, out result))
{
MyListBox.Items.Add(result); // Add Input to our ListBox.
}
else
{
sum = MyListBox.Items.Cast<int>().Sum(x => Convert.ToInt32(x));
MessageBox.Show("Sum is: " +sum);
}
// Clear InputBox.
InputTextBox.Text = String.Empty;
}

How to fetch data from dynamically created textboxes (windows application)

I have used the below code to dynamically create textboxes by giving the total number of textboxes initially. After i enter values to these textboxes, how can i fetch the values from it. Like if i give count as 3, 3 textboxes will be created. Now, i enter data to each textbox. How can i read the values i entered into these texboxes.
int a = 1;
public Form1()
{
InitializeComponent();
}
public System.Windows.Forms.TextBox AddNewTextBox()
{
System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
this.Controls.Add(txt);
txt.Top = a * 25;
txt.Left = 100;
txt.Name = "txt" + this.a.ToString();
txt.Text = "TextBox " + this.a.ToString();
a = a + 1;
return txt;
}
private void button1_Click(object sender, EventArgs e)
{
int i;
int count = Int16.Parse(counttxt.Text.ToString());
for (i = 1; i <= count; i++)
{
AddNewTextBox();
}
}
Hold a reference to the dynamically generated TextBox in a variable of type array or list.
Beside that if u want the value from TextBox that was named txt1
string value = this.Controls["txt1"].Text
string allTextBoxValues = "";
foreach (Control childc in Controls) {
if (childc is TextBox && childc.Name.Contains("txt"))
allTextBoxValues += ((TextBox)childc).Text + ",";
}

c# windows form application dynamic objects value

i have made a mistake of re-inventing the wheel. There are options
but somehow i like the feel of this.
Sorry but don't have enough rep to post an image.
This is how the form looks like:
SNO.-------ITEMS--------FROM--------TO---------QUANTITY // labels
[ 1 ]-------[-----------▼]---[--------]----[--------]------[-------------] {NEW} {DELETE} //textboxes and buttons
I've got the 'new' button click event to generate a row, and serial number to be automatic
and inserted the items into the collections from Properties panel.
Delete button deletes an entire row and shifts both the button up on Y position.
I need to assign the value of quantity [(TO - FROM ) + 1] in the QUANTITY text boxes,
for which i have the code as :
public void print_quant(object Sender, EventArgs e)
{
TextBox quanty;
quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0];
calculate_quant(this, e);
quanty = result;
}
public static string result;
public string calculate_quant(object sender, EventArgs e)
{
TextBox sfrom;
sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0];
TextBox sto;
sto = (TextBox)this.Controls.Find("STO" + count, true)[0];
TextBox quan;
quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0];
//if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text))
{
int to = Convert.ToInt32(sto.Text);
int from = Convert.ToInt32(sfrom.Text);
int quantity = (to - from) + 1;
result = quantity.ToString();
quan.Text = result;
}
return result;
}
count is initialized at 1 on form load, keeps increasing with number of rows
the same code works in the delete row method
public void delete_row(object sender, EventArgs e) //function to delete a row
{
TextBox snum;
snum = (TextBox)this.Controls.Find("SNO"+count, true)[0];
snum.Dispose();
...//delete other row elements
}
please help me figure out why it doesnt work for the print_quant / calculate_quant methods
I made some changes to your code. I changed the return on your calculate method to a string, and added a quanty.Text=calculatemethod line to your print method
public void print_quant(object Sender, EventArgs e)
{
TextBox quanty;
quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0];
//add this line
quanty.Text = calculate_quant(this, e).ToString();
}
public static string result;
//change this
//public void calculate_quant(object sender, EventArgs e)
//to
public string calculate_quant(object sender, EventArgs e)
{
TextBox sfrom;
sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0];
TextBox sto;
sto = (TextBox)this.Controls.Find("STO" + count, true)[0];
//this isn't being used here
//TextBox quan;
//quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0];
//if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text))
{
int to = Convert.ToInt32(sto.Text);
int from = Convert.ToInt32(sfrom.Text);
int quantity = (to - from) + 1;
return quantity.ToString();
}
}
Edit
try this.
Create a usercontrol and make it look exactly like one of your rows.
add a property variable for each of the boxes
//whenever you Sno="something" the textbox will automatically be updated.
private string _Sno="00000";
public string Sno{get{return _Sno;}set{_sno=value; SnoTextBox.Text=value;}}
do this for each of your textboxes.
on your main form now you can add a flowpanel, they a bit tricky at first. when you add your new Usercontrol to it, they will automatically be added from the top down, or up, or however you set it up.
When you want to add a new row, just add your new Usercontrol to the flowpanel
FlowPanel flowPanel =new FlowPanel();
FlowPanel.Controls.Add(new myUserControl());
to delete
FlowPanel.Controls.RemoveAt(2);
This is really poorly written, but I am out of time. Either ignore me altogether, or try to figure it out. Sorry I couldn't be more help.
this worked for me
private void textBox_TextChanged(object sender, EventArgs e)
{
TextBox quant;
int x = count - 1;
string num = Convert.ToString(x);
quant = (TextBox)this.Controls.Find("QUANTITY" + x , true)[0];
TextBox to = (TextBox)this.Controls.Find("STO" + x, true)[0];
TextBox from = (TextBox)this.Controls.Find("SFRM" + x, true)[0];
string tovalue = to.Text;
int to1 = Convert.ToInt32(tovalue);
string fromvalue = from.Text;
int from1 = Convert.ToInt32(fromvalue);
int result = (to1 - from1) + 1 ;
if (result > 0)
{
string result1 = Convert.ToString(result);
quant.Text = result1;
}
}
after adding
STO.TextChanged += new System.EventHandler(textBox_TextChanged);
at the function that was generating the boxes where i needed to calculate :)

How can I use text property of dynamic created textfield?

I have this code, which dynamically creates some textfields for me. k is taken from user btw.
for (int i = 0; i < k; i++)
{
TextBox t1 = new TextBox();
t1.Parent = groupBox2;
t1.Left = textBox2.Left;
t1.Top = textBox2.Top + (i + 1) * 40;
t1.Name = "text" + (i + 1);
t1.Enabled = true;
groupBox2.Controls.Add(t1);
}
What i want to do is, after this creating phase is done, when the user presses groupbox2's "OK" button, I want to take the created textfields' text properties, but so far I don't know how could this be done, since I gave textfields a name, I tried this but didn't work.
private void button3_Click(object sender, EventArgs e)
{
node1.name = textBox2.Text;
for (int i = 0; i < k; i++)
{
node1.array[i] = Convert.ToInt32("text"+(i+1).Text);
}
}
Any help would be nice, thanks.
Try this method:
private void button3_Click(object sender, EventArgs e)
{
node1.name = textBox2.Text;
for (int i = 0; i < k; i++)
{
TextBox txtBox = (TextBox)groupBox2.FindControl("text" + (i + 1));
if (txtBox != null)
{
node1.array[i] = txtBox.Text;
}
}
}
Loop through your text boxes in groupBox1 and get their names,Try this:
List<string> TextBoxesName=new List<string>();
foreach (Control item in groupBox1.Controls)
{
if (item is TextBox)
{
TextBoxesName.Add((item as TextBox).Text);
}
}
Set to your dynamic texboxes ID and than you can do groupBox2.FindControl("dynamic_texbox_id") to get your text box
Easiest solution is to put your listboxes in a collection of some sort
List<ListBox> listboxes = new List<ListBox>();
for (...)
{
...
listboxes.add(listbox);
}
Then you can refer back to them whenever you want
Or since you're adding them to a groupbox, why not go through that collection?

dynamic text box and append and save them to sql server DataBase

HI I have requirement that
1) display given no.of textboxes dynamically and save to DB
2) if I change the number then new textboxes should append to UI
EX: TextBox AddButton
If I give 2 in textbox and click on add
Then 2 textboxes should appear. I filled some data in those textboxes. Now When I change the value 2 to 5 then 3 more textboxes should append(condition:old textboxes data should retain)
If the second value is less than or equal to first value then do nothing.
My code is
void Append()
{
string Data = string.Empty;
TextBox tb;
if (Convert.ToInt32(hdnCnt.Value) < Convert.ToInt32(txtNoofGames.Text))
{
for (int i = 0; i < Convert.ToInt16(txtNoofGames.Text); i++)
{
if (i <= Convert.ToInt32(hdnCnt.Value))
{
tb = (TextBox)Form.FindControl("txtGame1");
Data = tb.Text;
}
TextBox Newtb = new TextBox();
Newtb.ID = "txtGame" + i;
Form.Controls.Add(Newtb);
if (i <= Convert.ToInt32(hdnCnt.Value))
{
Newtb.Text = Data;
}
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (hdnCnt.Value != "")
Append();
hdnCnt.Value = txtNoofGames.Text;
for (int i = 0; i < Convert.ToInt16(txtNoofGames.Text); i++)
{
TextBox tb = new TextBox();
tb.ID = "txtGame" + i;
Form.Controls.Add(tb);
}
}
I am getting exception "object reference not set to an instance of object" at Data = tb.Text; in append method.
You didn't initialize it from the looks of it
TextBox tb = new TextBox();
Hope that helps,
Instead of Form.Controls.Add(tb);
Please try with Page.Form.Controls.Add(tb);

Categories

Resources