This is application i am doing in c# web application
I am creating link buttons dynamically as below.
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
LinkButton ln = new LinkButton();
ln.Text = ds.Tables[0].Rows[i].ItemArray[0].ToString();
ln.ID = ds.Tables[0].Rows[i].ItemArray[1].ToString();
divonlne.Controls.Add(ln);
divonlne.Controls.Add(new LiteralControl("<br/>"));
}
my click event is as follows
ln.Click += new EventHandler(Clicked);
In my click event i am getting the linkbutton text and Id as follows
protected void Clicked(object sender, EventArgs e)
{
LinkButton lno = sender as LinkButton;
Session["Toname"] = lno.Text;
Session["idto"] = lno.ID;
}
But this is firing only when the last link button is clicked.
Can anyone help me out?
You already wrote how you subscribe the Click Event, but in your sample i cant see it.
Maybe you subscribe on the wrong place. This works...
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
LinkButton ln = new LinkButton();
ln.Text = ds.Tables[0].Rows[i].ItemArray[0].ToString();
ln.ID = ds.Tables[0].Rows[i].ItemArray[1].ToString();
ln.Click += new EventHandler(Clicked);
divonlne.Controls.Add(ln);
divonlne.Controls.Add(new LiteralControl("<br/>"));
}
When using dynamic controls in a custom control, remember to decorate your class with the INamingContainer interface. This ensures recreated controls fit correctly into the hierarchy and remember which events they are supposed to handle.
Related
I create buttons in my application by:
List<Button> btnslist = new List<Button>();
for (int i = 0; i < nbrofbtns; i++)
{
Button newButton = new Button();
btnslist.Add(newButton);
this.Controls.Add(newButton);
newButton.Width = btnsidelength;
newButton.Height = btnsidelength;
newButton.Top = btnsidelength
* Convert.ToInt32(Math.Floor(Convert.ToDouble(i / Form2.puzzlesize)));
newButton.Left = btnsidelength
* Convert.ToInt32(
Math.Floor(Convert.ToDouble(i))
- Math.Floor((Convert.ToDouble(i))
/ (Form2.puzzlesize)) * (Form2.puzzlesize));
newButton.BackgroundImage = Lights_out_.Properties.Resources.LightsOutBlack;
newButton.Tag = (i+1).ToString();
newButton.Click += new EventHandler(Any_Button_Click);
Then I have a method for when any of the buttons are clicked.
void Any_Button_Click(object sender, EventArgs e)
{
//the variable b has all the insformation that the single button had itself.
Button b = (Button)sender;
if (b.BackgroundImage == Lights_out_.Properties.Resources.LightsOutBlack)
{
MessageBox.Show(b.Tag.ToString());
MessageBox.Show(btnslist[Convert.ToInt32(b.Tag)].BackgroundImage.ToString());
btnslist[Convert.ToInt32(b.Tag)].BackgroundImage =
Lights_out_.Properties.Resources.LightsOutWhite;
MessageBox.Show(btnslist[Convert.ToInt32(b.Tag)].BackgroundImage.ToString());
}
else
{
MessageBox.Show("b.backgroundimage != lightsoutblack. Backgroundimage = "
+ b.BackgroundImage.ToString());
}
}
How do I change the data in the actual button (then said button is clicked)? I want specificly to change the backgroundimage. How could I do this?? (I also need to change the backgroundimage of some other buttons created by the code.)
The sender object is the button:
Button b = (Button)sender;
... so you should be able to change properties on it directly:
b.WhateverPropsToChange = yourSetting;
PS: I don't think this is necessary, but if the button is not updated directly, you might try to using b.Refresh() to let it know something has changed.
You're handling Click event of every button you've created - and sender in Any_Button_Click is actually the button was clicked.
So just change b.BackgroundImage to whatever you need.
I've created a RadGrid programmatically and tried to bind a BatchEditCommand to it, but it's not updating and disappear after clicking the save more than one. The BatchEditCommand is not fired at all, no knowing what event is firing, it's hard for me to debug, maybe I've missed out some important setting when creating RadGrid?
for (int i = 1; i <= 1; i++)
{
strategy = strategy + Convert.ToString(i);
RadGrid RadGrid_Strategy = new RadGrid();
RadGrid_Strategy.ID = strategy;
RadGrid_Strategy.Skin = "Office2010Blue";
RadGrid_Strategy.GridLines = System.Web.UI.WebControls.GridLines.Both;
RadGrid_Strategy.DataSource = GetDataTableForStrategy(CY, i);
RadGrid_Strategy.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.Top;
RadGrid_Strategy.ShowHeader = false;
RadGrid_Strategy.BatchEditCommand += new GridBatchEditEventHandler(RadGrid_BatchEditCommand);
RadGrid_Strategy.MasterTableView.EditMode = GridEditMode.Batch;
RadGrid_Strategy.MasterTableView.BatchEditingSettings.EditType = GridBatchEditingType.Cell;
RadGrid_Strategy.AllowAutomaticUpdates = true;
RadGrid_Strategy.MasterTableView.CommandItemSettings.ShowAddNewRecordButton = false;
RadGrid_Strategy.MasterTableView.CommandItemSettings.ShowSaveChangesButton = true;
RadGrid_Strategy.MasterTableView.CommandItemSettings.ShowCancelChangesButton = true;
PlaceHolder1.Controls.Add(RadGrid_Strategy);
RadGrid_Strategy.Rebind();
}
Where BatchEditCommand is not firing at all:
protected void RadGrid_BatchEditCommand(object sender, GridBatchEditingEventArgs e)
{...}
The event you're trying to call can only get fired if you make changes to your grid, then call any of these client-side functions from the RadGrid's BatchEditingManager:
saveChanges(tableView)
saveAllChanges()
saveTableChanges(tableViews)
Check out this thread on the Telerik forums for more info.
I have a CheckedListBox control that I created programatically from below...
Button btnSelectAll = new Button();
btnSelectAll.Text = "Select All";
btnSelectAll.Name = item.Id;
btnSelectAll.Tag = param.Id;
CheckedListBox chkListBox = new CheckedListBox();
chkListBox.Size = new System.Drawing.Size(flowPanel.Size.Width - lblListBox.Size.Width - 10, 100);
//set the name and tag for downstream event handling since two-way bindings are not possible with control
chkListBox.Tag = param.Id;
chkListBox.Name = item.Id;
chkListBox.ItemCheck += new ItemCheckEventHandler(chkListBox_ItemCheck);
btnSelectAll.Click += new EventHandler(btnSelectAll_Click);
Notice when I dynamically created the item, I also added an event handler whenever the ItemCheck on the chkListBox is hit. Somewhere else in the code... I do...
CheckedListBox tmpCheckedListBox = cntrl as CheckedListBox;
for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
tmpCheckedListBox.SetItemChecked(i, true);
}
When I do the above, it doens't raise the ItemChecked event. How do I raise this event such that it is as if a user clicked on the item?
One way is to just call the same method as assigned to the event and pass in the correct control for sender, for example:
for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
tmpCheckedListBox.SetItemChecked(i, true);
chkListBox_ItemCheck(tmpCheckedListBox.Items[i],null);
}
You can usually get away with passing EventArgs.Empty or null as the event arguments, however if you depend on them in the event handler you would need to construct the correct arguments class and pass that in, for example:
for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
var args = new ItemCheckEventArgs(i,true,tmpCheckedListBox.GetItemChecked(i));
tmpCheckedListBox.SetItemChecked(i, true);
chkListBox_ItemCheck(tmpCheckedListBox.Items[i],args);
}
I have associated a Button ID while generating Buttons dynamically and created a Button event handler as follows:
btn.Click += new EventHandler(btn_Click);
Button Click event:
protected void btn_Click(object sender,EventArgs e)
{
Button b = new Button();
b = (Button)sender;
string i = b.ID.Substring(b.ID.Length - 1, 1);
int j1 =Convert.ToInt32(i);
id1 = to[j1];
Page.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"),
"addScript", "PassValues('" + id1 + "')", true);
ScriptManager.RegisterStartupScript(this, this.GetType(),
"sendMessage", "javascript:sendMessage(); ", true);
}
However this event is not getting called i have placed all my controls inside an UpdatePanel
EDIT: What is happening is on button click somehow a function is getting called which is present on Page.Load
protected void getEntriesRight()
{
j = (int)Session["j"];
int n1 = j + 3;
for (; j <= n1; j++)
{
if (j < fr.data.Length)
{
HtmlGenericControl listItem = new HtmlGenericControl("li");
HtmlGenericControl a1 = new HtmlGenericControl("a");
Label anchor = new Label();
Image im = new Image();
btn = new Button();
im.ImageUrl = fr.data[j].pic_square;
im.Height = 45;
im.Width = 47;
btn.CssClass = "btn-add";
btn.Text = "Invite";
to[j] = fr.data[j].uid;
btn.ID = "btn" + j;
a1.Attributes.Add("href", "#");
anchor.Text = fr.data[j].name;
a1.Controls.Add(btn);
a1.Controls.Add(im);
a1.Controls.Add(anchor);
listItem.Controls.Add(a1);
list.Controls.Add(listItem);
btn.Click += new EventHandler(btn_Click);
}
}
Session["j"] = j;
}
Help!
Dynamically generated controls have to be recreated on every postback in order for their events to fire. This is one of the most commonly-encountered problems with generating controls programmatically in .NET, and it is discouraged if you can find a way around it.
For example, if you have a button that should only be present when another button is clicked, have the button in the page to begin with, and use the Visible property to control whether it is shown or not.
Regarding your edit. Every post-back to the server, even inside an UpdatePanel, is going to call Page_Load. If you want to detect whether a request has come from an UpdatePanel then you need to check !Page.IsAsync before calling the function.
I created dropdownlist at runtime when a button is clicked.and i palced another button to get the selected text from dynamic dropdownlist.When i try to retrieve the selected text from dropdownlist it gives me the error called object reference not set, following is my code.
TableRow tr;
TableCell tc;
DropDownList dp;
TextBox txt;
protected void Button1_Click(object sender, EventArgs e)
{
int no = int.Parse(TextBox1.Text);
for (int i = 0; i < no; i++)
{
tr = new TableRow();
tr.BorderStyle = BorderStyle.Groove;
for (int j = 0; j < 1; j++)
{
tc = new TableCell();
tc.BorderStyle = BorderStyle.Groove;
dp = new DropDownList();
//form1.Controls.Add(dp);
txt = new TextBox();
dp.Items.Add("hello");
tc.Controls.Add(dp);
tc.Controls.Add(txt);
tr.Cells.Add(tc);
}
Table1.Rows.Add(tr);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.Text =((DropDownList)this.FindControl("dp")).SelectedItem.Text;
}
You can't do it this way. Remember that on every request, you get a new page object, and new copies of all the controls in it. Any control you add dynamically must be added the same way every single time, otherwise it won't exist.
In this case, you add it once, when the button is clicked. When you click button2, a request is generated and a new page object is created that no longer has your dropdownlist, because it is only ever added in the button1 handler.
The easiest thing to do would be add your dropdownlist to the page normally but just set Visible to false. Then when they click button 1, set Visible to true. This will ensure that your dropdownlist will always be present.
Dynamic controls are tricky, and should be avoided when possible, especially if you're new to ASP.Net.
Actually, I was able to make it work..
I created a dataset ahead of the table creation, then:
tc = new TableCell();
dd= new DropDownList();
ddl.ID = dd1;
foreach (DataRow dr in dst.Tables[0].Rows)
{
ddl.Items.Add(new ListItem(dr["Text"].ToString(),dr["Value"].ToString()));
}
tcActions.Controls.Add(ddlActions);
I'm not an expert or anything, I just peck at it until I make it do what I want.