Postback on second click of button in UpdatePanel in asp.net - c#

I am creating a page in asp.net where an update panel is added dynamically, and few controls(button,table) are created and added to update panel dynamically.
Below is the piece of code:
UpdatePanel up = new UpdatePanel();
up.ID = newRequests.Tables[0].Rows[i].ItemArray[1].ToString() + "up" + i.ToString();
up.UpdateMode = UpdatePanelUpdateMode.Always;
// create table
HtmlGenericControl table=new HtmlGenericControl("table");
HtmlTableRow toprow = new HtmlTableRow();
HtmlTableCell topleftcell = new HtmlTableCell();
HtmlTableCell toprightcell = new HtmlTableCell();
// create button
Button add = new Button();
add.Text = "Approve";
add.ID = newRequests.Tables[0].Rows[i].ItemArray[1].ToString() + "btn" + i.ToString();
toprightcell.Controls.Add(add);
toprightcell.Controls.Add(new LiteralControl(" "));
// add trigger to update panel
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
trigger.ControlID = add.ID;
trigger.EventName = "Click";
up.Triggers.Add(trigger);
toprow.Controls.Add(topleftcell);
toprow.Controls.Add(toprightcell);
table.Controls.Add(toprow);
up.ContentTemplateContainer.Controls.Add(table);
div.Controls.Add(up);
divNR.Add(div);
Below is div tag where update panel is added dynamically.
<div id="div_AMContainer" runat="server" class="panelContainer">
</div>
Problem is:
When I click on button first time, there is no postback.
But on second click, page is reloaded.
Am I missing something here.?

Related

How to add CheckBox, Label and DDL to ASP.NET page programmatically?

I am trying to add a check box, label and DDL to ASP.NET page (aspx) from my back class in C#. I have been using LiteralControl _liText = new LiteralControl(); to attach label so that I can show them using this.Controls.Add(_liText);in CreateChildControls() method.
How do I add DDL and check box to ASp.NET page from C# code so that my label is in the same line with DDL and checkbox?
I have already made DDL using this syntax:
List<DropDownList> _ddlCollection=new List<DropDownList>();
for (int i = 0; i < 5; i++)
{
_ddlCollection.Add(new DropDownList());
}
Problem is not in this.Controls.Add() which I call from CreateChildControls(). It is OnPreRender() method where I fill ddl and check box. Is LiteralControl class good for this? Here is what I have tried in OnPReRender():
foreach (SPList list in web.Lists)
{
if (!list.Hidden)
{
_liText.Text += #<input type="checkbox">;
_liText.Text += list.Title + "<br />";
}
}
Your controls exist but the page or user control are not aware of them.
You need to add your control to the page
Page.Controls.Add(_ddlCollection);
You can also add your controls to other controls on the page, for example a panel.
panel1.Controls.Add(_ddlCollection);
You are adding a list of dropdowns which I don't think is what you want.
You need to add ListItems instead.
var dropDown = new DropDownList {Id = "dropDown1"};
dropDown.Items.Add(new ListItem("text", "value");
Page.Controls.Add(dropDown);
Add a label for the dropdown.
Page.Controls.Add(new Label {AssociatedControlId = dropDown.Id, Text = "Drop me down"});
For your other controls follow the same process:
Add a checkbox
Don't add an html control to a literal unless that is really what you want.
If you want to be able to access that checkbox in the code behind then you need to add it as an asp.net control. User a placeholder.
placeHolder1.Controls.Add(new CheckBox {Id = "chkBox", Text="Tick me"});
The text property on the checkbox will be the label for the check box and tick/untick the check box when you click on the text.
Output should be
<label for="dropDown1" >Drop me down</label>
<select id="dropDown1" >
<option value="value" >text</option>
</select>
<input type="checkbox" id="chkbox" />
<label for="chkbox" >Tick me</label>
First, you should add a placeholder.
<form id="form1" runat="server">
<asp:PlaceHolder runat="server" ID="phMain"></asp:PlaceHolder>
</form>
Next, if you have add in one line you use table (It is a simple but not recommended method, next step add all to Page and set css style for the page).
protected override void CreateChildControls()
{
base.CreateChildControls();
Table table = new Table();
for (int i = 0; i < 3; i++)
{
TableRow tr = new TableRow();
TableCell tc1 = new TableCell();
tc1.Controls.Add(new LiteralControl(String.Format("Line {0}",i)));
tr.Cells.Add(tc1);
TableCell tc2 = new TableCell();
CheckBox chb = new CheckBox();
chb.ID = String.Format("CheckBox_{0}", i);
chb.Text = String.Format("CheckBox {0}", i);
chb.CheckedChanged += chb_CheckedChanged;
chb.AutoPostBack = true;
tc2.Controls.Add(chb);
tr.Cells.Add(tc2);
TableCell tc3 = new TableCell();
DropDownList ddl = new DropDownList();
ddl.ID = String.Format("DropDownList_{0}", i);
ddl.Items.Add("1111");
ddl.Items.Add("2222");
ddl.Items.Add("3333");
ddl.SelectedIndex = i;
ddl.Enabled = false;
tc3.Controls.Add(ddl);
tr.Cells.Add(tc3);
table.Rows.Add(tr);
}
phMain.Controls.Add(table);
}
void chb_CheckedChanged(object sender, EventArgs e)
{
CheckBox chb = sender as CheckBox;
string ddlid = chb.ID.Replace("CheckBox", "DropDownList");
DropDownList ddl = this.Page.FindControl(ddlid) as DropDownList;
if (ddl != null)
{
ddl.Enabled = chb.Checked;
}
}

Dynamic C# Not rendering on page_load

I have a method which is intended to dynamically generate a series of divs based on the entry of a value from a dropdown list. However, I wish to reuse the same code to generate the tables on the first page_load when a number already exists.
This is where the method is called. It is called GenerateTables and it is called from the Page_Load event:
if (!IsPostBack)
{
AcademicProgramme programme;
if (Request.QueryString["id"] != null)
{
programme = academic.GetAcademicProgramme(Request.QueryString["id"]);
programmeName.Text = programme.Name;
PopulateView(programme);
GenerateTables(programme.Levels);
}
}
And here is the method itself (apologies for the size of the method):
private void GenerateTables(int count)
{
for (int i = 1; i < count + 1; i++)
{
LiteralControl title = new LiteralControl();
LiteralControl close = new LiteralControl();
LiteralControl close2 = new LiteralControl();
String script = "<div class=\"ModuleProgTable\"><h3>Level " + i + "</Modules></h3></br>";
title.Text = script;
AcademicTable.Controls.Add(title);
Panel panel = new Panel();
panel.ID = "Level" + i + "Modules";
PopulatePanel(panel, GetModulesSession(i));
Button a = new Button();
a.ID = "AddModule" + i;
a.Text = "Add Module";
a.Click += (OpenPopup);
AcademicTable.Controls.Add(panel);
AcademicTable.Controls.Add(a);
close.Text = "</div> <!-- Close here -->";
close2.Text = "</div>";
AcademicTable.Controls.Add(close);
}
}
The divs are clearly being populated because if I change the dropdown option then they appear on the PostBack without fail. It's when I try to get them to render on the first page_load that I am having problems.
Any feedback and advice would be greatly appreciated!
Regards,
-Michael

Dynamic Table in asp.net design

I built recently a table using c# and asp.net and I was facing design issues.
string name = Request.QueryString["name"];
AnimalsDB animal = new AnimalsDB();
DataSet ds = animal.GetFactByName(name);
TableRow rw = new TableRow();
TableCell tc1 = new TableCell();
Label l1 = new Label();
l1.Text = ds.Tables[0].Rows[0]["AName"].ToString();
Image image = new Image();
image.ImageUrl = ds.Tables[0].Rows[0]["Pic"].ToString();
image.Width = 250;
image.Height = 250;
Label l2 = new Label();
l2.Text = ds.Tables[0].Rows[0]["Fact"].ToString();
tc1.Width= 200;
tc1.Controls.Add(l1);
tc1.Controls.Add(image);
tc1.Controls.Add(l2);
rw.Cells.Add(tc1);
Table3.Rows.Add(rw);
The table is bit unorganized all the details appears on one line, do you have any idea how to sort it and organize the details.
(In my case I want to show the lable1 break-line image and break-line then the 2nd lable).
If all you have to display is three pieces of information, try something like this for your front end:
<h3><asp:Label ID="_animalName" runat="server"></asp:Label></h3>
<asp:Image ID="_animalImg" runat="server" />
<p><asp:Label ID="_animalFact" runat="server"></asp:Label></p>
And then your code behind:
_animalName.Text = ds.Tables[0].Rows[0]["AName"].ToString();
_animalImg.ImageUrl = ds.Tables[0].Rows[0]["Pic"].ToString();
_animalFact.Text = ds.Tables[0].Rows[0]["Fact"].ToString();

ASP.NET -> Adding a ButtonColumn to a DataTable or DataGridView (Programmatically)

Having the odd problem figuring out how to add a ButtonColumn to a DataTable (or, arguably, the DataGrid). All I want to do is be able to use the data from the datatable to tell a button to do something onClick, and I seem to be failing at it.
A google search did not show anything immediately useful, as they are all using ItemTemplates.
//dt.Columns.Add("Ajax Link", typeof(Literal));
ButtonColumn newButtonColumn = new ButtonColumn();
newButtonColumn.HeaderText = "Asp.Net Link";
dt.Columns.Add(); // Doesn't want newButtonColumn.
for (int i = 0; i < dt.Rows.Count; i++)
{
/*
Literal newAjaxLink = new Literal();
newAjaxLink.Text = "Test";//"<button type=\"button\" onclick=\"AjaxButton_onClick(" + dt.Rows[i]["UserInfoID"].ToString() + "); StoreUserInfoID(" + dt.Rows[i]["UserInfoID"].ToString() + "); ShowDiv();\">Ajax Link</button>";
dt.Rows[i]["Ajax Link"] = newAjaxLink; // #todo: HTML button that triggers an AJAX call for load the proper data into the fields. Also to make the DIV visible.
*/
Button newButton = new Button();
newButton.ID = dt.Rows[i]["UserInfoID"].ToString();
newButton.Text = "Asp.Net Link";
newButton.Click += new EventHandler(Button_Link_Click);
dt.Rows[i]["Asp.Net Link"] = newButton; //#todo: Just a button to open a new window with the proper ID.
}
Any ideas?
where are u adding the button to the respective thing?...seems u r just giving values to button,but not adding.
Try this
DataTable dt = new DataTable("Table");
DataColumn col = dt.Columns.Add("ID", typeof(Int32));
col.AllowDBNull = true;

get dynamically generated ajax textbox id

I have created a web application in which I need to generate textboxes depending upon the number the user enters.I have used Ajax and created textboxes dynamically but these textboxes are not accessible from code-behind.I have used find control but to no use.This is the code I use to generate textbox.
if (txtnobranches.Text != "")
{
if (Convert.ToInt32(txtnobranches.Text) != 0)
{
div_br.InnerHtml = "<table></table>";
tbl_br.Controls.Clear();
for (int i = 0; i < Convert.ToInt32(txtnobranches.Text); i++)
{
TableRow rowbr = new TableRow();
TableCell cellname = new TableCell();
cellname.Text = "Branch Location " + i.ToString();
rowbr.Cells.Add(cellname);
TableCell cellvalue = new TableCell();
cellvalue.Text = "";
TextBox txt = new TextBox();
txt.Text = "";
txt.ID = "txtbranchloc" + i.ToString();
cellvalue.Controls.Add(txt);
cellvalue.ID = "txtbranchloc" + i.ToString();
rowbr.Cells.Add(cellvalue);
tbl_br.Rows.Add(rowbr);
}
}
}
You can access the element by name using Request.Form["NameOfFormControl"] You will have to make little change in code.
In javascript
txt.Name = "txtbranchloc" + i.ToString();
In Code Behind
Note: Make sure you access it in postback otherwise you get null
if (Page.IsPostBack)
{
string firstTxtVal = Request.Form["txtbranchloc0"].ToString();
string secondTxtVal = Request.Form["txtbranchloc1"].ToString();
}
Using Request.Form Collection

Categories