How can I read a dynamically created textbox - c#

I create some dynamic textbox's and a button in a placeholder and would like to save info in textbox's when button is clicked but not sure how to retrieve data from the textbox
LiteralControl spacediv3 = new LiteralControl("&nbsp&nbsp");
Label lblComText = new Label();
lblComTitle.Text = "Comment";
TextBox txtComment = new TextBox();
txtComment.Width = 200;
txtComment.TextMode = TextBoxMode.MultiLine;
phBlog.Controls.Add(lblComText);
phBlog.Controls.Add(spacediv3);
phBlog.Controls.Add(txtComment);
Button btnCommentSave = new Button();
btnCommentSave.ID = "mySavebtnComments" ;
btnCommentSave.Text = "Save ";
phBlog.Controls.Add(btnCommentSave);
btnCommentSave.CommandArgument = row["ID"].ToString();
btnCommentSave.Command += new CommandEventHandler(btnSave_Click);
protected void btnSave_Click(object sender, CommandEventArgs e)
{
firstelement.InnerText = txtComment.text // this gives error on txtComment.text
}

You need to get a reference to your control in btnSave_Click. Something like:
protected void btnSave_Click(object sender, CommandEventArgs e)
{
var btn = (Button)sender;
var container = btn.NamingContainer;
var txtBox = (TextBox)container.FindControl("txtComment");
firstelement.InnerText = txtBox.text // this gives error on txtComment.text
}
You also need to set the ID on txtComment and recreate any dynamically created controls at postback.

You will need some mechanism to create a relation between the Button and the TextBox obviously. In winforms this would be easy, where each control has a Tag property, which can contain a reference to pretty much anything. The web controls don't have such a property (that I know of), but it is still easy to maintain such relations. One approach would be to have Dictionary in the page storing button/textbox relations:
private Dictionary<Button, TextBox> _buttonTextBoxRelations = new Dictionary<Button, TextBox>();
When you create the button and textbox controls, you insert them in the dictionary:
TextBox txtComment = new TextBox();
// ...
Button btnCommentSave = new Button();
// ...
_buttonTextBoxRelations.Add(btnCommentSave, txtComment);
...and then you can look up the text box in the button's click event:
protected void btnSave_Click(object sender, CommandEventArgs e)
{
TextBox commentTextBox = _buttonTextBoxRelations[(Button)sender];
firstelement.InnerText = txtComment.text // this gives error on txtComment.text
}

Try during postback to load txtComment (with the same ID) in overridden LoadViewState method after calling base.LoadViewState. In this case you do load it before postback data are handled and txtComment control comes loaded.

Add an 'ID' to the textbox
txtComment.ID = "txtComment"
Request the information from the submitted form (provided you have a form on the page)
comment = Request.Form("txtComment")

Related

Getting values from dynamically generated controls

I am generating wpf form dynamically. All the controls are generated dynamically as follows
A sample code snippet
String tbname = name;
TextBlock txtBlock1 = new TextBlock();
txtBlock1.Text = tbname;
Grid.SetRow(txtBlock1, count);
Grid.SetColumn(txtBlock1, icount);
SampleGrid.Children.Add(txtBlock1);
TextBox txtBox = new TextBox();
txtBox.Text = ptiAttribute.description;
txtBox.Name = tbname.Replace(" ", "");
DynamicGrid.RegisterName(txtBox.Name, txtBox);
Grid.SetRow(txtBox, count);
Grid.SetColumn(txtBox, icount+1);
SampleGrid.Children.Add(txtBox);
Attaching a button click event as follows
var Button = CreateButton("Save", 15, 3);
Button.Click += new RoutedEventHandler(button_Click);
SampleGrid.Children.Add(Button);
I would like to get all the control values (For example: The above text box has value Book), I have to get it after button click. I am not only having text box. I have combo box, date picker too. I don't know which name is registered (RegisterName). Every thing dynamic.
private static void button_Click(object sender, RoutedEventArgs e)
{
# How to get dynamic values here (text bx value, date picker value, combo box value)
}
Simply, how to get values from dynamically generated controls. I have gone through a lot of Visual tree links but I don't know how it works on button click.
Any simple code snippet will help me to move ahead. Thanks
I'm not used to WPF but try this approach(inspired by this):
private static void button_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
int row = Grid.GetRow(btn);
TextBox txtBox = SampleGrid.Children
.OfType<TextBox>()
.First(txt => txt.Name == name && Grid.GetRow(txt) == row);
// ...
}

Get the ID of the Grid

I have two ASP.NET Grid views, which contain an Image-button, which both call an Edit On-click event. the On-click event looks like:
protected void Edit(object sender, EventArgs e)
{
ImageButton ibtn1 = sender as ImageButton;
using (GridViewRow row = (GridViewRow)((ImageButton)sender).Parent.Parent)
{
txtMessageID.ReadOnly = true;
txtMessageID.Text = row.Cells[2].Text;
txtReference.Text = row.Cells[6].Text;
buttonClicked.Text = ibtn1.ID.ToString();
popup.Show();
}
}
which sole purpose is to fire off a ModalDialogBox, with key items from the grid view being clicked. My problem is that one of the grids doesn't have the Cells[6] (Reference) and therefore falls over. What i need to do is wrap a statement around this cell checking which grid (ID) the button click came from.
I'm not using Row-command, as this wouldn't allow for a single method call from multiple grids. My question is how do I obtain the Grid ID from the Image Button being clicked within this method (see above)?
ended up using the RowCommand of the Gridview, and then used the following to get what i need:
rotected void Edit(object sender, GridViewCommandEventArgs e)
{
ImageButton ibtn1 = sender as ImageButton;
GridView grd = sender as GridView;
string gridName = grd.ClientID;
string buttonId = e.CommandName;
using (GridViewRow row = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer)
{
txtMessageID.ReadOnly = true;
txtMessageID.Text = row.Cells[2].Text;
if (gridName == "grdMessageDups")
{
txtReference.Text = row.Cells[6].Text;
}
buttonClicked.Text = ibtn1.ID.ToString();
popup.Show();
}
}

Adding button to panel dynamically and getting it's parent ID

I created a page where I give admin's a way to change photos info (e.g. Title, Description, etc) All the controls on the page are added dynamically because I have more than one gallery of photos.
panel --> parent.
button .
title text box.
description text box.
In every panel, I have button that when clicked, sends the changed information to the server where the photo info is stored (Flickr). The click event for this button is added dynamically, and I want to know if is possible to get the parent of the Button I just clicked on.
Here is the code where I add all my controls:
//global veriables (this is only part of the code)
Panel panel;
Button button;
for (int i = 0; i < photo.Length; i++) {
photo[i] = new FlickerImages(photoSet.MediumURLS[i], photoSet.ThumbnailURLS[i], photoSet.Titles[i], photoSet.Descreption[i]);
panel = new Panel();
panel.ID = "panel" + i;
button = new Button();
button.ID = "sendDataButton" + i;
button.Text = "send data";
button.Click += button_Click; //adding the event
label = new Label();
label.ID = "editLabel" + i;
panel.Controls.Add(label);
panel.Controls.Add(photo[i].CurrentImage(i)); //Image control
panel.Controls.Add(photo[i].EditTitleTextBox(i)); //TextBox control
panel.Controls.Add(photo[i].EditCommentTextBox(i)); //TextBox control
panel.Controls.Add(button);
Form.Controls.Add(panel);
}
Here is the click event I add to all the buttons:
void button_Click(object obj, EventArgs e) {
Response.Write(button.Parent.ID); // i get panel10 every time this get fired.
}
I know this is possible with jQuery but is it possible to get the button ID in ASP.NET?
Sorry for my English and thanks for the help.
Not sure, but are you looking for the ClientID property? (button.Parent.ClientID)
Edit:
You should reference the sending button in the event handler:
void button_Click(object obj, EventArgs e)
{
Response.Write(((Button)obj).Parent.ID);
}

onClick for dynamically generated LinkButton

In my sharepoint web-part application. I am dynamically generating LinkButtons as below. and this works fine
foreach (var pName in productTypesNames[productType] )
{
var subLi = new HtmlGenericControl("li");
var linkButton = new LinkButton{ Text = pName };
linkButton.Click += new EventHandler(linkButton_Click);
subLi.Controls.Add(linkButton);
ul.Controls.Add(subLi);
}
However, when I click on one of the links in UI, my debugger never hits the breakpoint that is set at very first line of
void linkButton_Click(object sender, EventArgs e)
{
}
More Code
protected void StateClicked(object sender, CommandEventArgs e)
{
//Generate a dictionary of type Dictionary<string, List<string>>
//Display the dictionary
foreach (var productType in productTypesNames.Keys)
{
var li = new HtmlGenericControl("li");
nav.Controls.Add(li);
var ul = new HtmlGenericControl("ul");
var anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", "#");
foreach (var pName in productTypesNames[productType] )
{
var subLi = new HtmlGenericControl("li");
var linkButton = new LinkButton{ Text = pName };
linkButton.Click += new EventHandler(linkButton_Click);
subLi.Controls.Add(linkButton);
ul.Controls.Add(subLi);
}
anchor.InnerHtml = productType;
li.Controls.Add(anchor);
li.Controls.Add(ul);
}
}
Where stateClicked is called by a click on the image map of USA.
You probably aren't recreating the dynamically generated links on every postback.
If you have a if (!IsPostback) wrapped around your foreach, try removing it.
i had the same problem here ....
i was creating an HtmlTable after firing an event...
this table has (n) HtmlTableRows (calculated in the event handler)
now each row contains 2 LinkButtons that are generated from the code behind .. after an event is handled...
and each LinkButton is assigned a new event handler:
lnkbtnEdit.CommandArgument = b.BookID.ToString();
lnkbtnEdit.Click += new EventHandler(lnkbtnEdit_Click);
where lnkbtnEdit_Click signature is as follows:
protected void lnkbtnEdit_Click(object sender, EventArgs e)
the weird thing is that .. there is a postback when i click the generated LinkButton... but the event was not firing...
i don't know exactly what the problem was ... but i found the solution: ..
it appears as if these generated controls disappear on the postback (tried to assign an id and used Page.FindControl() witch returned with null !!)
so i had to re-link the buttons.... on the Page_Load i re-generated the LinkButtons, with same ID... and linked them to their respective EventHandlers

Create controls dynamically

I want to know if this is possible in c# winform.
create control when ever button is pressed and place it at given location.
I think it is possible like this
private TextBox txtBox = new TextBox();
private Button btnAdd = new Button();
private ListBox lstBox = new ListBox();
private CheckBox chkBox = new CheckBox();
private Label lblCount = new Label();
but the problem lies when ever button is pressed same name controls are created.How to avoid that
What da........
i wrote and no exception i was expecting it because control already contains btnAdd instead as many button create as many you want.
Accessing them will be issue but it will be solved by #drachenstern method correct?
private void button1_Click_1(object sender, EventArgs e)
{
Button btnAdd = new Button();
btnAdd.BackColor = Color.Gray;
btnAdd.Text = "Add";
btnAdd.Location = new System.Drawing.Point(90, 25+i);
btnAdd.Size = new System.Drawing.Size(50, 25);
this.Controls.Add(btnAdd);
i = i + 10;
}
int currentNamingNumber = 0;
txtBox.Name = "txtBox" + currentNamingNumber++;
Rinse, Repeat.
Gives each element a unique numeric name, allows you to find out how many elements have been created (notice that you don't want to decrement to track all created objects, because then you may create two elements with the same name).
I don't think you can pass the name you want into the new function, but you can always set the name after creating it.
You could try the solution I posted here. It will dynamically create 5 buttons in the constructor. Just move the code to the button click event and it should add the buttons dynamically and register with the Click events.
It sounds like your looking for a List<TextBox>.

Categories