Using variable in label name - c#

Can something like this be done?
var test = 1;
label+test+.Text = "Some text goes here...";
Which would result in:
label1.Text = "Some text goes here...";
I wouldn't mind using switch-case if I had few cases, but I have like 40 labels that I would like dynamically assigned text depending on the variable value.

Use Controls.Find() in your form.
void Button1Click(object sender, EventArgs e)
{
var test = 1;
var labels = Controls.Find("label" + test, true);
if (labels.Length > 0)
{
var label = (Label) labels[0];
label.Text = "Some text goes here...";
}
}

var test = 1;
Control label = this.FindControl("label" + test);
if(label != null)
{
label.Text = "Some text goes here...";
}
More informationon FindControl is available at,
https://msdn.microsoft.com/en-us/library/system.web.ui.control.findcontrol%28v=VS.100%29.aspx?f=255&MSPPError=-2147217396

I have like 40 labels that I would like dynamically assigned text
depending on the variable value
Here's another example, which is basically the same approach as Handoko's:
for(int i = 1; i <= 40; i++)
{
Label lbl = this.Controls.Find("label" + i.ToString(), true).FirstOrDefault() as Label;
if (lbl != null)
{
lbl.Text = "Hello Label #" + i.ToString();
}
}

Related

Get textbox name from stackpanel wpf

I have a stackpanel with dynamically created textboxes and buttons in my wpf application.
This works ok. Later in the application I have to use the name of the textboxes and the values. How do I do that.
I have this code:
First the creation of the textboxes i a stackpanel named panelBet.
Second a switch-case where the name and the value is used. Red lines under 'controls'.
First creation:
int f = 1;
foreach (TextBox txt2 in txtBet)
{
string name = "Bet" + f.ToString(); ;
txt2.Name = name;
txt2.Text = name.ToString();
txt2.Width = 100;
txt2.Height = 40;
txt2.Background = Brushes.Lavender;
txt2.Margin = new Thickness(3);
txt2.HorizontalAlignment = HorizontalAlignment.Left;
txt2.VerticalAlignment = VerticalAlignment.Top;
txt2.Visibility = Visibility.Visible;
panelBet.Children.Add(txt2);
f++;
}
Second switch-case:
private void cboRunder_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var cboRunder = sender as ComboBox;
string strRunder = cboRunder.SelectedValue.ToString(); // blinds, preflop osv.
switch (strRunder)
{
case "Blinds":
string s = ((TextBox)panelBet.Controls["txtBet"]).Text;
}
}
This should get you a reference to the TextBox named "txtBet" in the panelBet assuming there is one:
TextBox txtBet = panelBet.Children.OfType<TextBox>()
.FirstOrDefault(x => x.Name == "txtBet");

How to set a variable in a labelname

in my project i have 8 dynamic Textboxes and 8 dynamic Labels, which were created in c#.
Now i need to read the text in it and insert it in a db.
My current script looks like
Label labelname1 = this.Controls.Find("label1", false).FirstOrDefault() as Label;
Label labelname2 = this.Controls.Find("label2", false).FirstOrDefault() as Label;
Label labelname3 = this.Controls.Find("label3", false).FirstOrDefault() as Label;
.....
Is it possible, to create a while loop with a variable like:
int i = 1;
while (a < 9)
{
label Labelname+i = this.Controls.Find("label+i" + a, false).FirstOrDefault() as Label;
i++;
}
When I take the "labelname+i" it's not possible, because it isn't a string.
Thank you
Extract method then
private T FindControl<T>(string name) where T : Control {
return this
.Controls
.Find(name, false)
.OfType<T>()
.FirstOrDefault();
}
and use it in a loop (it seems you want for one):
for (int i = 1; i < 9; ++i) {
Label myLabel = FindControl<Label>($"label{i}");
if (myLabel != null) {
//TODO: Put relevant code here
}
}
Same loop if you want to enumerate TextBoxes:
// textBox1..textBox8
for (int i = 1; i < 9; ++i) {
TextBox myTextBox = FindControl<TextBox>($"textBox{i}");
if (myTextBox != null) {
//TODO: Put relevant code here
}
}
You can create a List of Labels and try like:
List<Label> labels = new List<Labels>();
for (int i=1;i<9;i++)
{
Label lbl = this.Controls.Find("label"+i.ToString(), false).FirstOrDefault() as Label;
labels.Add(lbl);
}
And if you want to access i Label you simply do:
labels[i] ...

String to Textbox

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";

How to manipulate controls created at runtime?

Suppose I have this in page load:
Label lblc = new Label();
for (int i = 1; i <= 10; i++)
{
lblc.Text = i.ToString();
this.Controls.Add(lblc);
}
How can I manipulate each of these controls at run time?
I want to:
Set/get their text.
Reference a particular control, in this case Label.
Use an array if you know how many labels you will have,
Label[] lblc = new Label[10];
for (int i = 0; i < 10; i++)
{
lblc[i] = new Label() { Text = (i + 1).ToString() };
this.Controls.Add(lblc[i]);
}
Then you will reference the textbox 1 with lblc[0] and textbox 2 with lblc[1] and so on. Alternatively if you do not know how many labels you will have you can always use something like this.
List<Label> lblc = new List<Label>();
for (int i = 0; i < 10; i++)
{
lblc.Add(new Label() { Text = (i + 1).ToString() });
this.Controls.Add(lblc[i]);
}
You reference it the same way as the array just make sure you declare the List or the array outside your method so you have scope throughout your program.
Suppose you want to do TextBoxes as well as Labels well then to track all your controls you can do it through the same list, take this example where each Label has its own pet TextBox
List<Control> controlList = new List<Control>();
for (int i = 0; i < 10; i++)
{
control.Add(new Label() { Text = control.Count.ToString() });
this.Controls.Add(control[control.Count - 1]);
control.Add(new TextBox() { Text = control.Count.ToString() });
this.Controls.Add(control[control.Count - 1]);
}
Good luck! Anything else that needs to be added just ask.
Your code creates only one control. Because, label object creation is in outside the loop. you can use like follows,
for (int i = 1; i <= 10; i++)
{
Label lblc = new Label();
lblc.Text = i.ToString();
lblc.Name = "Test" + i.ToString(); //Name used to differentiate the control from others.
this.Controls.Add(lblc);
}
//To Enumerate added controls
foreach(Label lbl in this.Controls.OfType<Label>())
{
.....
.....
}
Better to set the Name and then use that to distinguese between the controls
for (int i = 1; i <= 10; i++)
{
Label lblc = new Label();
lblc.Name = "lbl_"+i.ToString();
lblc.Text = i.ToString();
this.Controls.Add(lblc);
}
when:
public void SetTextOnControlName(string name, string newText)
{
var ctrl = Controls.First(c => c.Name == name);
ctrl.Text = newTExt;
}
Usage:
SetTextOnControlName("lbl_2", "yeah :D new text is awsome");

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