I add a label with its respective text to show dinamically using placeholder in ASP.NET coding C#, the next snippet is to show what I have for the time being
protected void Button1_Click(object sender, EventArgs e)
{
Label label1= new Label();
label1.ID="lbdin";
label1.Text="agregado dinamicamente";
TextBox textbox1 = new TextBox();
textbox1.Text = "textbox dinamico";
Button btn = new Button();
btn.ID = "btn";
btn.Text = "boton dinamico";
btn.Click += DynamicButton;
PlaceHolder1.Controls.Add(label1);
PlaceHolder1.Controls.Add(textbox1);
PlaceHolder1.Controls.Add(btn);
}
the controls appears dinamically in the placeholder, that works fine, my problem comes out when I try to retrive the text that the label control shows, in order to do that I've added a button and coded the next
protected void Button2_Click(object sender, EventArgs e)
{
Label Referencia_lb = PlaceHolder1.FindControl("lbdin") as Label;
//Label Referencia_lb = PlaceHolder1.FindControl("lbdin") as Label;
Referencia_lb.Text = "CAMBIANDO EL TEXTO DEL OBJETO CREADO EN TIEMPO DE EJECUCION";
}
but when debug the application I got the error
An exception of type 'System.NullReferenceException' occurred in WebApplication2.dll but was not handled in user code
could you please help me and tell me how to retrieve the text from the label that is created automatically into the placeholder
Replace the PlaceHolder1.FindControl("lbdin") as Label with:
var lbdin = PlaceHolder1.Children.Cast<Control>().FirstOrDefault(x => x.Id == "lbdin") as Label;
then you need to test for null.
if(lbdin != null)
{
lbdin.Text = "Your Text";
}
else
{ Response.Write("alert('could not find label');"); }
Related
I'm trying to change the text of a TextBox when I click a Button: both Controls are dynamically created as run-time.
The Buttons and the TextBoxes are created every time I click on another Button.
The Name Property for each control is specified by the User, using a TextBox.
For example, the user inputs "Test1", then the Button is named btn_Test1, and the TextBox is named txt_Test1.
The Button should open a FolderBrowserDialog and after a selection has been made, the TextBox shows the path selected.
I'm using the following code:
protected void button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
folderBrowserDialog.ShowDialog();
string TextName = button.Name.Replace("btn_", "txt_");
TextBox selectText = new TextBox();
selectText = this.Controls[TextName] as TextBox;
selectText.Text = folderBrowserDialog.SelectedPath;
}
however this part gives me null:
selectText = this.Controls[TextName] as TextBox;
I did check with the debugger when I create the controls, so TextName is setting the correct Name.
The Buttons and TextBoxes are inserted in a TabControls, the Tab Name is set to the value the user inputs, so the main TabControl gets 2 controls.
I'm using a hidden TabControl named "TabFolders" that will be the main reference for creating tab clones
I'm using this code:
private void CreateDynamicPathButtons(string TabName)
{
TabPage MyNewTab = new TabPage(TabName);
TabPage TabCopy1;
tabControlEmpresas.TabPages.Add(MyNewTab);
TabControl tc = new TabControl();
tc.Location = new System.Drawing.Point(6, 6);
tc.Size = TabFolders.Size;
for (int i = 0; i < TabFolders.TabCount; i++) {
TabFolders.SelectTab(i);
TabCopy1 = new TabPage(TabFolders.SelectedTab.Text);
foreach (Control c in TabFolders.SelectedTab.Controls) {
Control cNew = (Control)Activator.CreateInstance(c.GetType());
cNew.Text = c.Text;
cNew.Size = c.Size;
cNew.Location = new System.Drawing.Point(c.Location.X, c.Location.Y);
cNew.Visible = true;
if (cNew is TextBox) {
cNew.Name = "txt_" + MyNewTab.Text + "_" + TabFolders.SelectedTab.Text;
}
if (cNew is Button) {
cNew.Name = "btn_" + MyNewTab.Text + "_" + TabFolders.SelectedTab.Text;
cNew.Click += new EventHandler(button_Click);
}
TabCopy1.Controls.Add(cNew);
}
tc.TabPages.Add(TabCopy1);
}
MyNewTab.Controls.Add(tc);
}
After many attempts I did find a very simple solution.
TextBox selectText = new TextBox();
selectText = button.Parent.Controls[TextName] as TextBox;
The button parent hast all the controls.
Assuming that button is the Button control you're creating at run-time you mentioned, you're creating a TextBox control but you're not adding it to the Form.Controls collection (this.Controls.Add([Control])).
Also, you should assign a Location, using a logic that fits your current Layout, to position the newly created Controls. Otherwise, all new controls will be positioned one on top of the other. In the example, the new Control position is determined using a field (int ControlsAdded) that keeps track of the number of Controls created at run-time and add some basic layout logic.
But, if you want to keep a reference of these new Controls, you should add them to a List<Control> or some other collection that allows to select them if/when required.
int ControlsAdded = 0;
protected void button_Click(object sender, EventArgs e)
{
TextBox selectedText = new TextBox();
selectedText.Size = new Size(300, this.Font.Height);
selectedText.Location = new Point(100, ControlsAdded * selectedText.Height + 30);
ControlsAdded += 1;
this.Controls.Add(selectedText);
selectedText.BringToFront();
using (var fBD = new FolderBrowserDialog()) {
if (fBD.ShowDialog() == DialogResult.OK)
selectedText.Text = fBD.SelectedPath;
}
}
with selectText = this.Controls[TextName] as TextBox;, you are trying to find button with replaced name which is not available in this case, and hence it returns null. This is logical mistake.
also string TextName = button.Name.Replace("btn_", "txt_"); does not replace button name, it just assigns replaced string to TextName.
The proper implementation would be
protected void button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
folderBrowserDialog.ShowDialog();
button.Name = button.Name.Replace("btn_", "txt_");
TextBox selectText = new TextBox();
selectText = this.Controls[button.Name] as TextBox;
selectText.Text = folderBrowserDialog.SelectedPath;
}
I have created one winform app in which, on click of button, textbox will be generated. Now I have to add speech for these textboxes. For example if textbox's text is 'hello' there will be speech saying 'hello'.
I have tried this so far. :
private void btnAdd_Click(object sender, EventArgs e)
{
TextBox textbox = new TextBox();
int count = panel1.Controls.OfType<TextBox>().ToList().Count;
textbox.Location = new System.Drawing.Point(60, 25 * count);
textbox.Size = new System.Drawing.Size(220, 20);
textbox.Multiline = true;
textbox.Name = "textbox_" + (count + 1);
//textbox.TextChanged += new System.EventHandler(this.TextBox_Changed);
panel1.Controls.Add(textbox);
}
private void Form1_Load(object sender, EventArgs e)
{
SpVoice vc = new SpVoice();
vc.Speak(textbox1.Text, SpeechVoiceSpeakFlags.SVSFDefault);
}
I am using speechLib library for speech. Working fine in simple cases.
But when textbox is being created dynamically, I cannot access its ID or Name.
If the textbox is created in the button click event, then in the form_load event it doesn't exist, so you cannot use it as input for your voice library.
However, when you create the TextBox you could add a value for the property Tag.
For example
private void btnAdd_Click(object sender, EventArgs e)
{
TextBox textbox = new TextBox();
.....
textbox.Name = "textbox_" + (count + 1);
textbox.Tag = "SPEECH";
....
panel1.Controls.Add(textbox);
}
Now, when you need to retrieve this dynamically created textbox and use your voice library you could write this. But for the example I use an event handler for a different button
private void AnotherButton_Click(object sender, EventArgs e)
{
TextBox txt = panel1.Controls
.OfType<TextBox>()
.FirstOrDefault(x =x.Tag.ToString() == "SPEECH");
if (txt != null)
{
SpVoice vc = new SpVoice();
vc.Speak(txt.Text, SpeechVoiceSpeakFlags.SVSFDefault);
}
else
{
MessageBox.Show("Press the create button first!");
}
}
If you want, you could also use the same button event handler. Check if the control with the specified Tag exists and if not create it, if yes execute the voice Speak call.
private void btnAdd_Click(object sender, EventArgs e)
{
TextBox txt = panel1.Controls
.OfType<TextBox>()
.FirstOrDefault(x =x.Tag.ToString() == "SPEECH");
if (txt != null)
{
SpVoice vc = new SpVoice();
vc.Speak(txt.Text, SpeechVoiceSpeakFlags.SVSFDefault);
}
else
{
TextBox textbox = new TextBox();
.....
textbox.Name = "textbox_" + (count + 1);
textbox.Tag = "SPEECH";
....
panel1.Controls.Add(textbox);
}
}
EDIT
This assumes there is only one textbox with the SPEECH tag set. If you want more than one textbox then you should be able to tell which one you want to 'talk' (adding a little button on the right side of the textbox with a speaker image?) or loop over all the textboxes with the SPEECH tag and call Speak for each one
Something like this
var speechBoxes = panel1.Controls
.OfType<TextBox>()
.Where(x =x.Tag.ToString() == "SPEECH");
if (speechBoxes != null)
{
SpVoice vc = new SpVoice();
foreach(TextBox txt in speechBoxes)
{
vc.Speak(txt.Text, SpeechVoiceSpeakFlags.SVSFDefault);
// Not sure if you need also to add this call ....
vc.WaitUntilDone(10000);
}
}
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 adding text boxes dynamically and trying to capture data entered in text box on button click. but what is happening is , though I entered the data in the text box, when I clicked the button, the page is getting loaded and the control is getting created again. As a result , I am loosing the data in the text box. Can you tell me how can I capture this data entered to the dynamically created text boxes.
My sample code is as follows:
protected void Page_Load(object sender, EventArgs e)
{
Table tblTextboxes = new Table();
for(int i=0;i<10;i++)
{
TableRow tr=new TableRow();
TableCell tc=new TableCell();
TextBox tb=new TextBox();
tb.ID=i.ToString();
tc.Controls.Add(tb);
tr.Cells.Add(tc);
TableCell tc1=new TableCell();
LinkButton lnk=new LinkButton();
lnk.ID=i.ToString()+tb.Text+"lnk";
lnk.Text = "Show";
lnk.Click+=new EventHandler(lnk_Click);
tc1.Controls.Add(lnk);
tr.Cells.Add(tc1);
tblTextboxes.Rows.Add(tr);
}
placeTest.Controls.Add(tblTextboxes);
}
void lnk_Click(object sender, EventArgs e)
{
LinkButton lnk=sender as LinkButton;
Label lbl=new Label();
lbl.Text="The text is"+lnk.ID;
placeTest.Controls.Add(lbl);
}
LinkButton ID is changed every time you enter text into TextBox and post back.
One thing you want to make sure when creating control dynamically is - you want to recreate them with same ID when post back.
Updated Solution (to retrieve text from TextBox)
protected void Page_Load(object sender, EventArgs e)
{
var tblTextboxes = new Table();
for (int i = 0; i < 10; i++)
{
var tr = new TableRow();
var tc = new TableCell();
var tb = new TextBox {ID = i.ToString()};
tc.Controls.Add(tb);
tr.Cells.Add(tc);
var tc1 = new TableCell();
// This is a fix for - lnk.ID=i.ToString()+tb.Text+"lnk";
var lnk = new LinkButton {ID = i + "lnk", Text = "Show"};
lnk.Click += lnk_Click;
tc1.Controls.Add(lnk);
tr.Cells.Add(tc1);
tblTextboxes.Rows.Add(tr);
}
placeTest.Controls.Add(tblTextboxes);
}
void lnk_Click(object sender, EventArgs e)
{
var lnk = sender as LinkButton;
var lbl = new Label();
lbl.Text = "LinkButton ID: " + lnk.ID;
// Get number value from string
string id = Regex.Replace(lnk.ID, #"[^\d]", "");
// Retrieves a TextBox control by ID
var control = FindControlRecursive(Page, id);
if (control != null)
{
var textbox = control as TextBox;
lbl.Text += "; TextBox Text: " + textbox.Text;
}
placeTest.Controls.Add(lbl);
}
public Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
Based on the MSDN, I would recommend to use Page class's Init event. Look in to the title View State and Dynamically Added Controls for explanation. Also, I would recommend to add dynamic controls at the end of all existing controls. Create table first, and then add the text boxes.
I modified your code. It worked for me. I used VS 2012, .Net 4.5
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now.ToString());
}
protected void Page_Init(object sender, EventArgs e)
{
Table tblTextboxes = new Table();
for (int i = 0; i < 10; i++)
{
TableRow tr = new TableRow();
TableCell tc = new TableCell();
TextBox tb = new TextBox();
tb.ID = i.ToString();
tc.Controls.Add(tb);
tr.Cells.Add(tc);
//TableCell tc1 = new TableCell();
//LinkButton lnk = new LinkButton();
//lnk.ID = i.ToString() + tb.Text + "lnk";
//lnk.Text = "Show";
//lnk.Click += new EventHandler(lnk_Click);
//tc1.Controls.Add(lnk);
//tr.Cells.Add(tc1);
tblTextboxes.Rows.Add(tr);
}
placeTest.Controls.Add(tblTextboxes);
}
protected void Button1_Click(object sender, EventArgs e)
{
}
I had code to find label in gridview and I checked on it,s label text and it gives me the index not text and this error apear object refrence not set to ..... so I wnat to give CU.Username = LBL.Text; text no index of control
code
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
LblRseult.Visible = true;
LblRseult.Text = "Successfully Process";
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
cUser CU = new cUser(this);
LBL = (Label)GridView1.Rows[e.RowIndex].Cells[1].FindControl("Label1");
CU.Username = LBL.Text;
if (CU.BasiclyExists())
{
LblRseult.Visible = true;
LblRseult.Text = "This user already exists";
}
}
You can access control inside TemplateField this way:
Label lbl = GridView1.Rows[e.RowIndex].FindControl("Label1") as Label;