I have a dynamic tab where I have checkboxes. I put an event onCheckedChanged on them. It works first time, but after postback, my tab is recreated and when I click on another checkbox, I get more than one event being triggered.
Here is the code to create the tab :
private void initCatalog()
{
foreach (Article art in listArticle)
{
TableRow ligne = new TableRow();
ligne.Width = Unit.Percentage(100);
TableCell celluleITMREF = new TableCell();
celluleITMREF.Width = Unit.Percentage(10);
celluleITMREF.Text = art._ITMREF;
TableCell celluleCBOX = new TableCell();
celluleCBOX.Width = Unit.Percentage(8);
CheckBox cbox = new CheckBox();
cbox.ID = "cbox." + f._FOURNISSEUR + "." + art._ITMREF;
cbox.Checked = hfArticlesPaniers.Value.Contains(cbox.ID);
//cbox.Enabled = !(hfArticlesPaniers.Value.Contains(cbox.ID));
cbox.CheckedChanged += new EventHandler(cbox_CheckedChanged);
cbox.AutoPostBack = true;
cbox.CssClass = "c";
celluleCBOX.Controls.Add(cbox);
ligne.Cells.Add(celluleITMREF);
ligne.Cells.Add(celluleCBOX);
tabArticle.Rows.Add(ligne);
}
}
Here is the event for the checkbox :
protected void cbox_CheckedChanged(object sender, EventArgs e)
{
CheckBox c = sender as CheckBox;
Response.Write("<script>alert(\"" + c.ID + "\");</script>");
}
Here is the page_Load event :
protected void page_Load(object sender, EventArgs e){
this.initCatalog();
}
Thanks for your help :)
Each iteration of art in listArticle will cause the event handler to be added to the event by the line
cbox.CheckedChanged += new EventHandler(cbox_CheckedChanged);
executing each time. (i.e. you're adding the handler multiple times)
In addition, each running of initCatalog will also cause this if the page is not destroyed and loaded again in between.
Move the above line to a place where it will only be executed once after the page loads.
EDIT
on re-reading your code, adding multiple times within the loop is probably what you intended as there are multiple checkboxes. But after the postback, the initCatalog() may be executed again, thereby adding the event once more?
I found the mistake. I've a method who order the list after she was create ... I deleted the method and it worked.
I don't know why it made mistakes ...
private void orderCatalog()
{
var tab = from TableRow tr in tabArticle.Rows
orderby tr.Cells[1].Text
select tr;
List<TableRow> l = new List<TableRow>();
foreach (TableRow tr in tab)
{
l.Add(tr);
}
tabArticle.Rows.Clear();
foreach (TableRow tr in l)
{
tabArticle.Rows.Add(tr);
}
}
Related
I'm having a problem to get controls/ controls id that I have created manually from code behind. after doing research I found if I create the table and its all component including any controls in Page_Init() method, when rendering after postback the text value of textbox control should be available to the page. i tried to locate the textbox control using FindControl() method. when debugging it only reach to the line where I tried to locate the control using FindControl() and then throw an exception "Object reference not set to an instance of an object" bellow is the Page_Init() method
protected void Page_Init(object sender, EventArgs e)
{
Table tb = new Table();
tb.ID = "Table1";
TableRow row1 = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
TableCell cell3 = new TableCell();
TextBox txtbx = new TextBox();
Button btn = new Button();
cell1.Text = "Name: ";
txtbx.ID = "table1_text_input";
txtbx.ValidationGroup = "rosy";
cell2.Controls.Add(txtbx);
btn.Text = "Get the input";
btn.ValidationGroup = "rosy";
btn.Click += getBoxinput_Click;
cell3.Controls.Add(btn);
// adding cells to row1
row1.Cells.Add(cell1);
row1.Cells.Add(cell2);
row1.Cells.Add(cell3);
// adding row to table1
tb.Rows.Add(row1);
Panel1.Controls.Add(tb);
}
below is the button click event that supposes to display the control id and its text. I'm stuck with this for the last couple of days. any help will be appreciated.
protected void getBoxinput_Click(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
Table t = (Table)Page.FindControl("Panel1").FindControl("Table1");
TextBox tbox;
foreach (TableRow tr in t.Rows)
{
foreach (TableCell tc in tr.Cells)
{
foreach (Control cnt in tc.Controls)
{
if (cnt.GetType() == typeof(TextBox))
{
tbox = (TextBox)cnt;
display.Text += "control id: " + tbox.ID + " control input: " + tbox.Text + "<br/>";
}
}
}
}
}
}
catch (NullReferenceException ex)
{
display.Text += ex.Message;
}
}
Maybe I am missing something but why don't you just put all the controls in the global scope of the class (instead of just creating the instances inside Page_Init) so that you can access them in any part of your class. Of course I am assuming that Page_Init and getBoxinput_Click are in the same class.
EDIT:
Here is the example on how to put the variables in the global scope:
Table tb; //Declare variables outside any function.
protected void getBoxinput_Click(object sender, EventArgs e)
{
tb = new Table(); //Initialize them inside a function.
}
This way you will be able to access tb inside any function.
Your code is working perfectly. Here is what I used for the form markup:
<form id="form1" runat="server">
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Label ID="display" runat="server"></asp:Label>
</form>
I have a small ASP web application which can be used to determine whether or not 2 users have been assigned the same seat number.
To display the results / functionality, I decided to go with an asp:Table, where each row has 2 buttons (one for each user).
The administrator can click either one of the buttons to clear that user's seat number value from the system.
Here is the code which builds the table cells:
BuildDuplicateTable (called in Page_Load)
private void BuildDuplicateTable(List<Duplicate> duplicates)
{
foreach (var dup in duplicates)
{
var row = new TableRow();
var user1cell = new TableCell();
var seatcell = new TableCell();
var user2cell = new TableCell();
var button1 = new Button();
button1.Text = $"{dup.UserOne.UserName}";
var button1cell = new TableCell();
button1cell.Controls.Add(button1);
button1.Click += new EventHandler(Test);
var button2 = new Button();
button2.Text = $"{dup.UserTwo.UserName}";
var button2cell = new TableCell();
button2cell.Controls.Add(button2);
button2.OnClientClick = "return true";
button2.Click += (sender, eventArgs) =>
{
ActiveDirectory.ClearProperty(dup.UserTwo.UserName, "extensionAttribute2");
};
user1cell.Text = dup.UserOne.UserName;
seatcell.Text = dup.UserOne.SeatNumber;
user2cell.Text = dup.UserTwo.UserName;
row.Cells.Add(button1cell);
row.Cells.Add(seatcell);
row.Cells.Add(button2cell);
MyAspTable.Rows.Add(row);
}
}
My issue is that when I click on any of the buttons, the page is simply refreshed, and the data is no longer displayed (as I am handling postback in Page_Load). My event handler never fires ... Notice that in the code above I left in 2 separate methods of attaching an event handler that I tried - neither of them works!
Duplicate
class Duplicate
{
public UserSeatNumberRelationship UserOne;
public UserSeatNumberRelationship UserTwo;
public Duplicate(UserSeatNumberRelationship userone, UserSeatNumberRelationship usertwo)
{
UserOne = userone;
UserTwo = usertwo;
}
}
UserSeatNumberRelationship
class UserSeatNumberRelationship
{
public string UserName;
public string SeatNumber;
public UserSeatNumberRelationship(string username, string seatnumber)
{
UserName = username;
SeatNumber = seatnumber;
}
}
Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
DuplicateList = FindDuplicates();
BuildDuplicateTable(DuplicateList);
}
Test
protected void Test(object sender, EventArgs e)
{
ActiveDirectory.ClearProperty(UserName, "extensionAttribute2");
}
As ConnersFan mentioned in the comments, this was being caused by my PostBack handler in Page_Load.
So after removing this line
if (Page.IsPostBack) return;
The event handlers work fine.
I'm adding dropdownlists to my page depending on a amount of database entries and when I press the button I want to get the selected values in each dropdownlist.
I tried this
foreach(DropDownList a in Form.Controls.OfType<DropDownList>())
{
Response.Write(a.SelectedValue);
}
but it doesn't find any dropdownlist on the page. Below is the code I use to add the dorpdownlists.
protected void Page_Init()
{
string product = Request.QueryString["product"];
foreach (productoption r in dbcon.GetOption(product))
{
TableRow row = new TableRow();
TableCell cel1 = new TableCell();
TableCell cel2 = new TableCell();
DropDownList dropdown1 = new DropDownList();
dropdown1.CssClass = "productdropdown";
foreach (suboption f in dbcon.GetSubOption(r.ProductOptionID))
{
dropdown1.Items.Add(f.SubOptionName + " +$" +f.SubOptionPrice);
}
cel1.Text = "<b>" + r.OptionName + "</b>";
cel2.Controls.Add(dropdown1);
row.Cells.Add(cel1);
row.Cells.Add(cel2);
Table1.Rows.Add(row);
}
TableRow row2 = new TableRow();
TableCell cell3 = new TableCell();
Button cartbutton = new Button();
cartbutton.ID = product;
cartbutton.CssClass = "btn_addcart";
cartbutton.Click += cartbutton_OnClick;
cartbutton.Text = "Add to cart";
cell3.Controls.Add(cartbutton);
row2.Cells.Add(cell3);
Table1.Rows.Add(row2);
}
foreach (TabelRow row in Table1.Rows)
{
if(row.Cells.Count > 0)
{
if (row.Cells[1].Controls.Count > 0 && row.Cells[1].Controls[0].GetType() == typeof(DropDownList))
{
Response.Write(a.SelectedValue);
}
}
}
First you should make a function that looks for a control type in a ControlCollection and returns a list of found controls. Something like that:
public List<T> GetControlsOfType<T>(ControlCollection controls)
{
List<T> ret = new List<T>();
try
{
foreach (Control control in controls)
{
if (control is T)
ret.Add((T)((object)control));
else if (control.Controls.Count > 0)
ret.AddRange(GetControlsOfType<T>(control.Controls));
}
}
catch (Exception ex)
{
//Log the exception
}
return ret;
}
and then you can get all DropDownList like that:
List<DropDownList> ret = GetControlsOfType<DropDownList>(this.Page.Controls);
I hope it helped.
You should be adding controls inside another control for example a panel
*Also you dont need to define controls at page init, you can do that at page load and they will retain their value*
protected void Page_Load(object sender, EventArgs e)
{
loadControls();
}
//For Instance lets take a dropdownlist and add it to a panel named testpanel
Protected void loadControls()
{
DropdownList ddlDynamic = new DropdownList();
//give this control an id
ddlDynamic.Id = "ddlDynamic1"; // this id is very important as the control can be found with same id
//add data to dropdownlist
//adding to the panel
testpanel.Controls.Add(ddlDynamic);
}
//Now we have to find this control on post back for instance a button click
protected void btnPreviousSet_Click(object sender, EventArgs e)
{
//this will find the control here
//we will you the same id used while creating control
DropdownList ddlDynamic1 = testpanel.FindControl("ddlDynamic1") as DropdownList;
//can resume your operation here
}
Trying to add buttons programmatically to a webform.
Some work - others don't.
In the code below I add btnY and btnX in the Page_Load.
These both work - they show on the page and fire the event
and the code in the event handler works....
In the page load I also run bindData which gets a DataTable
and uses the data to create controls.
in the example I am only creating Button.
These buttons will appear on the page correctly but when clicked
they only do a postback ..
the code in the event handler doesn't work - does it get called?
The event handler is the same for all the buttons.
Any ideas why or how I can make it work?
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(btn("btnY", "Y"));
Pages P = new Pages();
bindData(P.DT);
PlaceHolder1.Controls.Add(btn("btnX", "X"));
}
Button btn(string id, string text)
{
Button btn1 = new Button();
btn1.ID = id;
btn1.Text = text;
btn1.Click += new System.EventHandler(this.btn_click);
return btn1;
}
protected void bindData(DataTable dt)
{
foreach (DataRow row in dt.Rows)
{
render(Convert.ToInt32(row["PageKey"]));
}
}
protected void render(int pageKey)
{
PlaceHolder1.Controls.Add(btn("btn_" + pageKey.ToString(), "Edit"));
}
protected void btn_click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string id = btn.ID;
Pages P = new Pages();
bindData(P.DT);
lt.Text = "ID=" + id;
}
Never mind .. figured it out .. example above should work, my actual code had a if (!Page.PostBack) that caused the problem
I'm creating textboxes in the Page_Load event and giving them values, however whenever I load the details I am getting the same output. I always seem to get the first output I got, even on subsequent searches.
Here's what my code with the irrelevant information missing:
Textbox txtName = New Textbox();
protected void Page_Load(object sender, EventArgs e)
{
LoadData();
}
void LoadData()
{
txtName.Text = DropDownList.SelectedValue;
tableCell.Controls.Add(txtName);
}
If DropDownList has two values (e.g. "Item 1" and "Item 2") and has autopostback enabled, first time it will generate and show "Item 1" in the textbox (the default value for the DropDownList), but if this is changed and the autopostback fires, the textbox does not change.
I've tried getting around this by creating a new TextBox, overriding the "LoadPostData" function to prevent this from loading, which got around the issue there, but then I couldn't view the data afterwards.
Any idea how I could get around this? I may be approaching this in the wrong way.
Edit: I've added another item to DropDownList that removes TextBox, so that it can be re-created again. It seems to show the correct data when it is re-created after being removed, but if I'm attempting to just edit it, this isn't updating correctly.
Edit2: Here's the rest of the code for this page in case this helps at all. The objects which I'm having issues with are SBUName and SBUComments, which are both TextBoxes. The same issue is also happening for SBUClientDropdown but I believe the resolution will be similar:
DBHandler DBHandler = new DBHandler();
List<string> clients = new List<string>();
List<string> clientGroups = new List<string>();
List<string> sbus = new List<string>();
// Objects for SBU changes
string previousSBU = "";
string previousSBUClient = "";
TextBox SBUName = new TextBox() { ID = "SBUName" };
TextBox SBUComments = new TextBox() { ID = "SBUComments" };
DropDownList SBUClientDropdown = new DropDownList();
protected void Page_Load(object sender, EventArgs e)
{
clients = DBHandler.GetClients();
clientGroups = DBHandler.GetClientGroups();
if (!Page.IsPostBack)
{
foreach (string client in clients)
{
SBUClientList.Items.Add(GenerateItem(client));
ClientList.Items.Add(GenerateItem(client));
}
foreach (string clientGroup in clientGroups)
ClientGroupList.Items.Add(GenerateItem(clientGroup));
}
if ((SBUClientList.SelectedValue.ToString() != previousSBUClient) || (SBUList.SelectedValue.ToString() != previousSBU))
{
previousSBUClient = SBUClientList.SelectedValue.ToString();
previousSBU = SBUList.SelectedValue.ToString();
sbus = DBHandler.GetSBUs(SBUClientList.SelectedValue);
SBUList.Items.Clear();
foreach (string sbu in sbus)
SBUList.Items.Add(GenerateItem(sbu));
LoadSBU();
}
}
void LoadSBU()
{
if ((SBUClientList.SelectedValue.Trim().Length > 0) && (SBUList.SelectedValue.Trim().Length > 0))
{
Entity thisSBU = DBHandler.GetSBUInformation(SBUClientList.SelectedValue, SBUList.SelectedValue);
SBUTable.Rows.Add(GenerateHeaderRow("Client Name", "SBU Name", "Comments"));
SBUClientDropdown.Items.Clear();
foreach (string client in clients)
SBUClientDropdown.Items.Add(GenerateItem(client));
SBUClientDropdown.SelectedValue = SBUClientList.SelectedValue;
SBUClientDropdown.SelectedIndex = SBUClientList.SelectedIndex;
TableCell SBUClientCell = new TableCell();
SBUClientCell.Controls.Add(SBUClientDropdown);
SBUName.Text = thisSBU.sSBUName;
TableCell SBUNameCell = new TableCell();
SBUNameCell.Controls.Add(SBUName);
SBUComments.Text = thisSBU.sSBUComments;
TableCell SBUCommentsCell = new TableCell();
SBUCommentsCell.Controls.Add(SBUComments);
SBUTable.Rows.Add(GenerateRow(SBUClientCell, SBUNameCell, SBUCommentsCell));
Button SBUSaveButton = new Button();
SBUSaveButton.Click += new EventHandler(this.SBUSaveChanges);
SBUSaveButton.Text = "Save SBU Changes";
TableCell SBUButtonCell = new TableCell();
SBUButtonCell.Controls.Add(SBUSaveButton);
SBUButtonCell.ColumnSpan = 3;
TableRow SBUFooter = GenerateRow(SBUButtonCell);
SBUFooter.TableSection = TableRowSection.TableFooter;
SBUTable.Rows.Add(SBUFooter);
}
}
void ShowMessage(string message)
{
OutputString.Text = "<div class=\"message\">" + message + "</div>";
}
ListItem GenerateItem(string input)
{
ListItem output = new ListItem();
output.Text = input;
return output;
}
TableCell GenerateCell(string text)
{
TableCell output = new TableCell();
output.Text = text;
return output;
}
TableRow GenerateRow(params TableCell[] cells)
{
TableRow output = new TableRow();
foreach (TableCell cell in cells)
output.Cells.Add(cell);
return output;
}
TableRow GenerateHeaderRow(params string[] columns)
{
TableRow output = new TableRow();
output.TableSection = TableRowSection.TableHeader;
foreach (string column in columns)
{
TableCell thisCell = new TableCell();
thisCell.Text = column;
output.Cells.Add(thisCell);
}
return output;
}
previousSBUClient and previousSBU will always be blank on each post back, so why do you compare against them on the Page_Load? If you want their values saved between postbacks you need to save them in ViewState, I suggest code like:
public string PreviousSBU
{
get { return Convert.ToString(ViewState["PreviousSBU"] ?? string.Empty); }
set { ViewState["PreviousSBU"] = value; }
}
Perhaps its because you add multiple header rows to the table, and only the contents between the first through the second get displayed? Any header rows after added don't get displayed?
On each postback you add a new header row. But the TextBox's are created on each postback and not saved between, so you shouldn't be seeing anything at all if thats the case.
To render txtName to the page, you should have something like:
this.Controls.Add(txtName); somewhere on the page, preferably in the Page_Init, though for what you've listed, at least before the LoadData() call in Page_Load.
Taking a guess at the missing code but are you databinding your dropdown list? If you are you may be doing it every time instead of just when the page is not a postback. Like I say, guessing at what's not in your question but you might want consider something like this instead:
if (!Page.IsPostback)
{
MyDropDownList.DataSource = blah;
MyDropDownList.DataBind();
}
myTextBox.Text = MyDropDownList.SelectedValue;
Create your controls in OnInit event, becouse viewstate serialization happens between oninit and onload. Also check if it is postback, to avoid overwriting values from viewstate.
I remember strange things happening if you don't supply an ID to the textbox, are you doing this?
txtName.ID="txtName";`