ASP.NET Dynamically created controls in C#: failed events - c#

I am creating a web application that requires controls to be created dynamically on the click of a button, and then add the controls to an already constructed asp:table.
The problem is that the events for the dynamic controls do not fire (ciDD_SelectedIndexChanged).
In order: the button is clicked, it sets a Session variable for the control IDs, creates the controls, then adds them to the table row. This is done OnClick, and OnInit for post back.
Is there an easy way to set the event for the dynamic controls, or am I going about this in a horrible way?
The button and it's event:
<asp:ImageButton ID="addHardware" runat="server" ImageUrl="~/Images/plus.png" Height="24" Width="24" OnClick="addHardware_Click" ImageAlign="AbsMiddle" style="margin-left:7px" Visible="false" />
protected void addHardware_Click(object sender, ImageClickEventArgs e)
{
Session["rowCount"] = (Convert.ToInt32(Session["rowCount"]) + 1);
CreateControls(Convert.ToInt32(Session["rowCount"]));
CreateRow(Convert.ToInt32(Session["rowCount"]));
}
The Control creation function and the list they are saved to:
private static List<Control> _controls = new List<Control>();
private static List<Control> HWControls
{
get { return _controls; }
}
protected void CreateControls(int i)
{
DropDownList ci = new DropDownList();
ci.AutoPostBack = true;
ci.ID = "ciDD" + i;
ci.SelectedIndexChanged += new EventHandler(this.ciDD_SelectedIndexChanged);
ci.Items.Add(new ListItem("", ""));
ci.Items.Add(new ListItem("test1", "test1"));
ci.Items.Add(new ListItem("test2", "test2"));
DropDownList dt = new DropDownList();
dt.ID = "deviceTypeDD" + i;
DropDownList m = new DropDownList();
m.ID = "modelDD" + i;
TextBox qt = new TextBox();
qt.ID = "qtTB" + i;
DropDownList dv = new DropDownList();
dv.ID = "deviceNumDD" + i;
TextBox sn = new TextBox();
sn.ID = "serialTB" + i;
HWControls.Add(ci);
HWControls.Add(dt);
HWControls.Add(m);
HWControls.Add(qt);
HWControls.Add(dv);
HWControls.Add(sn);
}
The Row creation function, and it's corresponding List:
private static List<TableRow> _rows = new List<TableRow>();
private static List<TableRow> Rows
{
get { return _rows; }
}
protected void CreateRow(int i)
{
TableRow row = new TableRow();
TableCell cell = new TableCell();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
TableCell cell3 = new TableCell();
TableCell cell4 = new TableCell();
TableCell cell5 = new TableCell();
cell.Controls.Add(HWControls.Find(x => x.ID.Contains("ciDD" + i)));
cell1.Controls.Add(HWControls.Find(x => x.ID.Contains("deviceTypeDD" + i)));
cell2.Controls.Add(HWControls.Find(x => x.ID.Contains("modelDD" + i)));
cell3.Controls.Add(HWControls.Find(x => x.ID.Contains("qtTB" + i)));
cell4.Controls.Add(HWControls.Find(x => x.ID.Contains("deviceNumDD" + i)));
cell5.Controls.Add(HWControls.Find(x => x.ID.Contains("serialTB" + i)));
row.Cells.Add(cell);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
row.Cells.Add(cell3);
row.Cells.Add(cell4);
row.Cells.Add(cell5);
Rows.Add(row);
hardwareTable.Rows.Add(row);
}
The OnInit to recreate the controls/rows after post back:
protected override void OnInit(EventArgs e)
{
int i = Convert.ToInt32(Session["rowCount"]);
if (i != 0)
{
for (int j = 1; j <= i; j++)
{
CreateControls(j);
CreateRow(j);
}
}
base.OnInit(e);
}

I found that creating the eventhandlers in the PreInit phase solved the issue.
protected void Page_PreInit(object sender, EventArgs e)
{
foreach (Control c in HWControls)
{
if(c.ID.Contains("ciDD"))
{
((DropDownList)c).SelectedIndexChanged += new EventHandler(this.ciDD_SelectedIndexChanged);
}
else if (c.ID.Contains("deviceTypeDD"))
{
((DropDownList)c).SelectedIndexChanged += new EventHandler(this.deviceTypeDD_SelectedIndexChanged);
}
}
}

Related

Gridview Footer Calcucation

I have 5 GridViews on a page. All of them show different table data, and show calculation of totals in footer.
But I need calculate all data from all GridViews and show it in a Label.
[]
use OnRow Created..
Declare variables at the top
double Counter;
double GrandTotalCounter;
this is sample code refer and make change in yours..
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
bool IsGrandTotalRowNeedtoAdd = false;
if ((strPreviousRowID != string.Empty) && (DataBinder.Eval(e.Row.DataItem, "city_name") == null))
{
IsGrandTotalRowNeedtoAdd = true;
intTotalIndex = 0;
}
if (IsGrandTotalRowNeedtoAdd)
{
GridView grdViewProducts = (GridView)sender;
GridViewRow GrandTotalRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert);
GrandTotalRow.Font.Bold = true;
GrandTotalRow.BackColor = System.Drawing.Color.LightPink;
GrandTotalRow.ForeColor = System.Drawing.Color.White;
TableCell HeaderCell = new TableCell();
HeaderCell.Text = "Grand Total";
HeaderCell.HorizontalAlign = HorizontalAlign.Left;
HeaderCell.ColumnSpan = 3;
HeaderCell.Font.Bold = true;
HeaderCell.ForeColor = System.Drawing.Color.Red;
HeaderCell.Font.Size = 10;
GrandTotalRow.Cells.Add(HeaderCell);
// you can use how many fields you want to calculate
HeaderCell = new TableCell();
HeaderCell.Text = string.Format("{0:0.00}", GrandTotalCounter);
HeaderCell.HorizontalAlign = HorizontalAlign.Right;
HeaderCell.Font.Bold = true;
HeaderCell.ForeColor = System.Drawing.Color.Red;
HeaderCell.Font.Size = 10;
GrandTotalRow.Cells.Add(HeaderCell);
//////////////
GrandTotalRow.Cells.Add(HeaderCell);
grdViewProducts.Controls[0].Controls.AddAt(e.Row.RowIndex,
GrandTotalRow);
}}
on RowDataBound
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
strtotalID = DataBinder.Eval(e.Row.DataItem, "city_name").ToString();
double TtCounter = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "CounterAmt").ToString());
TotalCounter += TtCounter;
GrandTotalCounter += TCounter;
/// Add how much you want
}

asp.net c# event handler not working second time

I have an asp.net web page that contain panel that will filled up on run time
protected void Page_Load(object sender, EventArgs e)
{
buildStructure(1);
}
and this is the method
public void buildStructure(int level_id)
{
pMain.Controls.Clear();
//Response.Write(#"<script language='javascript'>alert('" + level_id + "');</script>");
DataUtility DU = new DataUtility(#"****");
DataTable dt = DU.GetDataTable("SELECT * FROM dbo.PRStructure_Main WHERE level_id = "+level_id);
int curr_level = 1;
int curr_child = 1;
int totalchild = 0;
if (dt.Rows.Count > 0)
{
Panel pLevel = new Panel();
pLevel.CssClass = "level";
Panel pItem = new Panel();
pItem.CssClass = "item-ceo";
Label lItem = new Label();
lItem.Text = dt.Rows[0].ItemArray[2].ToString();
pItem.Controls.Add(lItem);
pLevel.Controls.Add(pItem);
pMain.Controls.Add(pLevel);
Panel pLevelLine = new Panel();
pLevelLine.CssClass = "level";
Panel pItemLine = new Panel();
pItemLine.CssClass = "item-line-ceo";
Panel pLine = new Panel();
pLine.CssClass = "horizontal-line";
pItemLine.Controls.Add(pLine);
pLevelLine.Controls.Add(pItemLine);
pMain.Controls.Add(pLevelLine);
Panel pLevelLine2 = new Panel();
pLevelLine2.CssClass = "level";
Panel pLevel2 = new Panel();
pLevel2.CssClass = "level";
dt = DU.GetDataTable("SELECT * FROM dbo.PRStructure_Main WHERE level_parent = "+(Convert.ToInt32( dt.Rows[0].ItemArray[0].ToString())));
lbItem2 = new LinkButton[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
Panel pItemLine2 = new Panel();
Panel pLine2 = new Panel();
if (i == 0)
{
pItemLine2.CssClass = "item-line-level2-first";
pLine2.CssClass = "horizontal-line2-first";
}
else if (i == dt.Rows.Count - 1)
{
pItemLine2.CssClass = "item-line-level2-last";
pLine2.CssClass = "horizontal-line2-last";
}
else
{
pItemLine2.CssClass = "item-line-level2-middle";
pLine2.CssClass = "horizontal-line2-middle";
}
pItemLine2.Controls.Add(pLine2);
pLevelLine2.Controls.Add(pItemLine2);
Panel pItem2 = new Panel();
pItem2.CssClass = "item-level2";
Panel pItemContent2 = new Panel();
pItemContent2.CssClass = "item-level2-content";
lbItem2[i] = new LinkButton();
lbItem2[i].Text = dt.Rows[i].ItemArray[2].ToString();
int current_level1 = (int)dt.Rows[i].ItemArray[0];
//lbItem2.OnClientClick = "alert('" + current_level1 + "')";
//lbItem2.Click += new EventHandler((s,e) => evHandler(s,e, current_level1));
lbItem2[i].Click += new System.EventHandler(delegate(Object o, EventArgs a)
{
evHandler(o, a, current_level1);
});
pItemContent2.Controls.Add(lbItem2[i]);
//pLevel.Controls.Add(lbItem);
DataTable dt2 = DU.GetDataTable("SELECT * FROM dbo.PRStructure_Main WHERE level_parent = " + dt.Rows[i].ItemArray[0]);
Panel pMenuLevel = new Panel();
pMenuLevel.CssClass = "menu-level2";
//<div class="menu-level2-items">Assets Integrity Management</div>
for (int j = 0; j < dt2.Rows.Count; j++)
{
Panel pMenuLevelItems = new Panel();
pMenuLevelItems.CssClass = "menu-level2-items";
LinkButton lbMenuItem = new LinkButton();
lbMenuItem.Text = dt2.Rows[j].ItemArray[2].ToString();
int current_level2 = (int)dt2.Rows[j].ItemArray[0];
//lbMenuItem.Click += new EventHandler(delegate (Object o, EventArgs ee) { evHandler(s, ee,current_level2)});
lbMenuItem.Click += new EventHandler(delegate (Object o, EventArgs a)
{
evHandler(o, a, current_level2);
});
pMenuLevelItems.Controls.Add(lbMenuItem);
DataTable dt3 = DU.GetDataTable("SELECT * FROM dbo.PRStructure_Main WHERE level_parent = " + dt2.Rows[j].ItemArray[0]);
Panel pSubMenuLevel = new Panel();
pSubMenuLevel.CssClass = "sub-menu-level2";
// <div class="sub-menu-level2-items"> Business Application Section </div>
for (int k = 0; k < dt3.Rows.Count; k++)
{
Panel pSubMenuLevelItems = new Panel();
pSubMenuLevelItems.CssClass = "menu-level2-items";
LinkButton lbSubMenuItem = new LinkButton();
lbSubMenuItem.Text = dt3.Rows[k].ItemArray[2].ToString();
int current_level3 = (int)dt3.Rows[k].ItemArray[0];
lbMenuItem.Click += new EventHandler((s, e) => evHandler(s, e, current_level3));
pSubMenuLevelItems.Controls.Add(lbSubMenuItem);
pSubMenuLevel.Controls.Add(pSubMenuLevelItems);
}
pMenuLevelItems.Controls.Add(pSubMenuLevel);
pMenuLevel.Controls.Add(pMenuLevelItems);
}
pItemContent2.Controls.Add(pMenuLevel);
pItem2.Controls.Add(pItemContent2);
pLevel2.Controls.Add(pItem2);
}
pMain.Controls.Add(pLevelLine2);
pMain.Controls.Add(pLevel2);
}
}
I have a problem in this section
lbMenuItem.Click += new EventHandler((s, e) => evHandler(s, e, current_level3));
and this is the handler method
public void evHandler(Object s,EventArgs e, int someData){
//Response.Write(#"<script language='javascript'>alert('" + someData + "');</script>");
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),"err_msg","alert('" + someData + "');",
true);
buildStructure(someData);
}
it work properly first time
but when i click it again its make page load.
I think your page_load should be like below
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack){
buildStructure(1);
}
}
You need to recreate the exact same controls when posting back. If the page loads with only one control how will it know to raise the click event for a control that doesn't exists.
Edit:
From what I understand about asp.net page life cycle, you must have the controls created before post back data is restored, that's how page control events fire. So if you have a control say LinkButtonA which was dynamically created on the page and you click on it, for the click event to trigger on the server during the post back, it must be recreated before post back data is restored, therefore try Recreating dynamic controls in Page_Init instead of Page_Load and try to keep the input to your method "buildStructure" the same. Say if you have called it from the event handler with buildStructure("fifth_level") make sure that Page_Init does the same buildStructure("fifth_level").
Microsoft recommends to create the dynamic controls on preint so you need to create the same controls on preinit like this
http://msdn.microsoft.com/en-us/library/ms178472.aspx
protected override void OnPreInit(EventArgs e)
{
}

Unable to SetFocus on a dynamically created text box

I am generating the text boxes dynamically.Table rows are created dynamically too, and these text boxes are added to those dynamically created row cells and they are added to the table using the following code
protected override void OnInit(EventArgs e)
{
PopulateTextBoxes();
SetFocus();
base.OnInit(e);
}
protected void PopulateTextBoxes()
{
int quantityRequired = 0;
quantityRequired =GetQuantity();
for (int j = 0; j < quantityRequired; j++)
{
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
TextBox tb = new TextBox();
tb.ID = j.ToString() +"_RowTbx"
tb.AutoPostBack = true;
tb.TextChanged += new EventHandler(tb_TextChanged);
cell1.Controls.Add(tb);
row.Cells.Add(cell1);
TableCell cell2 = new TableCell();
CheckBox chBox = new CheckBox();
chBox.CheckedChanged += new EventHandler(chBox_CheckedChanged);
chBox.AutoPostBack = true;
cell2.Controls.Add(chBox);
row.Cells.Add(cell2);
TableCell cell3 = new TableCell();
Image img = new Image();
img.Width = Unit.Pixel(25);
img.Height = Unit.Pixel(25);
img.ImageUrl = "HttpRuntime.AppDomainAppVirtualPath" + "/Images/" +"img.jpeg";
cell3.Controls.Add(img);
row.Cells.Add(cell3);
tbl_Serial.Rows.Add(row);
}
LoadDataIfExists();
}
private void tb_TextChanged(object sender, EventArgs e)
{
//I have implemented code to validate the text entered in the text box.
}
protected void SetFocus()
{
int emptytbxRow = 0;
TextBox tbx = new TextBox();
for (int i = 0; i < tbl_Serial.Rows.Count; i++)
{
string tbxId = i.ToString() + "_RowTbx";
string text = ((TextBox)tbl_Serial.Rows[i].Cells[0].FindControl(tbxId))).Text;
if (text == null || text==string.Empty)
{
tbx=((TextBox)(tbl_Serial.Rows[i].Cells[0].FindControl(tbxId)));
if (tbx != null)
tbx.Focus();
}
}
protected void LoadDataIfExists()
{
List<string> lstData=Service.GetData(int someNum)
for (int j = 0; j < lstData.Count; j++)
{
string tbxID = j.ToString() + "_RowTbx";
TextBox tbx = (TextBox)tbl_Serial.Rows[j].Cells[0].FindControl(tbxID);
tbx.Text = lstData[j];
}
}
When I debug, the tbx.focus seems to hit rightly but i do not see the cursor blinking on the text box in my UI.I do not know if I am missing something imp. Thank you.
Edit: Sorry I was not clear. When the page loads, the text boxes may contain data, but not all text boxes contain data. So whenever the page loads there are a few text boxes with data and there are empty ones. I want the cursor to be at the first empty box.
Given that you know which text box is your first empty one you want to also be aware of the page life cycle. OnInit is to early in the page life cycle for this to occur as the page is still initializing and the objects haven't yet rendered to the form. Try OnLoad or use PreRender to set focus to your item right before the form is rendered.
The link below will show you all available methods that you can hook into during the cycle.
ASP Page Lifecycle
For some unknown reason , C#code with the same logic as below did not work, while javascript works. Hope the following helps someone in future. Thank you Liqua for providing the start.
window.onload = function () {
FindWhichTextBoxIsEmpty();
}
function FindWhichTextBoxIsEmpty() {
var tableSerial = document.getElementById('tbl_Serial');
for (var i = 0; i < tableSerial.rows.length-1; i++) {
var ID = i.toString() + "_RowTbx";
if (document.getElementById(ID).value!="") {
var tb = document.getElementById(ID).value;
if (tb != "") {
if (i + 1 < tableSerial.rows.length-1) {
var nextID = (i + 1).toString() + "_RowTbx";
document.getElementById(nextID).focus();
}
}
}
}
}
didn't got your question clearly, what i got is you created a textbox dynamically, and trying to focus it at runtime.. May be this work for you try creating tb += getFocus event, or try tb.Focus();

Need to access dynamic controls ids inside the update panels

I am populating dynamic controls inside the update panel. The steps are
Step 1: Dynamic controls are populated inside dynamic table like this which is inside panel
<asp:Panel ID="pnlShowDDF" runat="server" Visible="False" ViewStateMode="Enabled">
</asp:Panel>
Step 2:
protected void loadTable()
{
HtmlTable tblDDF = new HtmlTable();
var objDDF = new ddf();
var dsDdfDetail = "DataSet Loaded"
if (dsDdfDetail.Tables[0].Rows.Count > 0)
{
int RowsCount = dsDdfDetail.Tables[0].Rows.Count;
for (int i = 0; i < RowsCount; i++)
{
HtmlTableRow tblNewRow = new HtmlTableRow();
HtmlTableCell tblDdfCell = new HtmlTableCell();
tblDdfCell1.Controls.Add(addCheckbox(dsDdfDetail.Tables[0].Rows[i][0].ToString()));
//The addCheckbox function returns the checkbox with its text
tblNewRow.Controls.Add(tblDdfCell);
tblDDF.Controls.Add(tblNewRow);
}
HtmlTableRow htFooterRow = new HtmlTableRow();
HtmlTableCell htFooterCell = new HtmlTableCell();
htFooterCell.Controls.Add(DelButton());
//DelButton() is written in below
htFooterCell.Attributes.Add("class", "pnlFooterRow");
htFooterCell.ColSpan = 2;
htFooterRow.Cells.Add(htFooterCell);
tblDDF.Controls.Add(htFooterRow);
}
pnlShowDDF.Controls.Add(tblDDF);
pnlShowDDF.Visible = true;
}
protected Button DelButton()
{
var btnDelete = new Button();
btnDelete.ID = "btnDelete";
btnDelete.Text = "De-Allocate";
btnDelete.Click += new EventHandler(btnDelete_Click);
btnDelete.Attributes.Add("class", "button");
btnDelete.ViewStateMode = ViewStateMode.Enabled;
return btnDelete;
}
Step 3 Need to access dynamic checkbox id from the btnDelete
void btnDelete_Click(object sender, EventArgs e)
{
//Need to access the checkbox id's here
foreach(Control chk in pnlShowDDF.Controls)
{
if(chk is CheckBox)
{
CheckBox chkbx= chk as CheckBox;
if(chkbx.Checked)
{
//Here i need to access the id's which i can't right now
}
}
}
}
Step 4: i have recalled the loadTable function on OnInit but no gains
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
loadTable();
}
What should be done so that i can access the checkbox id's ??
Whenever you add dynamic controls, you have to add them in Page_Init event and assign them proper IDs, so that when a postback occurs, those dynamic added controls are created again along with their values and will be accessible in other events, in your case btnDelete_Click.
So what you are missing is assigning IDs to the table cells and rows, I hope you are assigning ID to the checkboxes.
========================= EDIT ============================
Here is the code that is working with me, btnDelete_Click has good enough changes in it. I am getting the checkboxes that I added in and if I check any of them, i get the value as true.
protected void loadTable()
{
HtmlTable tblDDF = new HtmlTable();
//var objDDF = new ddf();
//DataSet dsDdfDetail = new DataSet();
//if (dsDdfDetail.Tables[0].Rows.Count > 0)
//{
//int RowsCount = dsDdfDetail.Tables[0].Rows.Count;
for (int i = 0; i < 5; i++)
{
HtmlTableRow tblNewRow = new HtmlTableRow();
HtmlTableCell tblDdfCell = new HtmlTableCell();
tblDdfCell.Controls.Add(addCheckbox(i.ToString()));
//The addCheckbox function returns the checkbox with its text
tblNewRow.Controls.Add(tblDdfCell);
tblDDF.Controls.Add(tblNewRow);
}
HtmlTableRow htFooterRow = new HtmlTableRow();
HtmlTableCell htFooterCell = new HtmlTableCell();
htFooterCell.Controls.Add(DelButton());
//DelButton() is written in below
htFooterCell.Attributes.Add("class", "pnlFooterRow");
htFooterCell.ColSpan = 2;
htFooterRow.Cells.Add(htFooterCell);
tblDDF.Controls.Add(htFooterRow);
//}
pnlShowDDF.Controls.Add(tblDDF);
pnlShowDDF.Visible = true;
}
protected Button DelButton()
{
var btnDelete = new Button();
btnDelete.ID = "btnDelete";
btnDelete.Text = "De-Allocate";
btnDelete.Click += new EventHandler(btnDelete_Click);
btnDelete.Attributes.Add("class", "button");
//btnDelete.ViewStateMode = ViewStateMode.Enabled;
return btnDelete;
}
protected CheckBox addCheckbox(string id)
{
CheckBox chk = new CheckBox();
chk.ID = id;
return chk;
}
void btnDelete_Click(object sender, EventArgs e)
{
//Need to access the checkbox id's here
foreach (Control chk in pnlShowDDF.Controls)
{
if (chk is HtmlTable)
{
HtmlTable tbl = (HtmlTable)chk;
foreach (HtmlTableRow row in tbl.Rows)
{
foreach (HtmlTableCell cell in row.Cells)
{
foreach (Control chk1 in cell.Controls)
{
if (chk1 is CheckBox)
{
CheckBox chkbx = chk1 as CheckBox;
if (chkbx.Checked)
{
//Here i need to access the id's which i can't right now
}
}
}
}
}
}
}
}

Adding new eventHandler in RadioButton CheckedChanges in dynamic table

I'm trying to add another eventHandler to RadioButton. This is the sample code (which is working):
ASP.NET:
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" Text="Button" />
C#:
protected void Page_Load(object sender, EventArgs e)
{
RadioButton RB1 = new RadioButton();
RB1.ID = "1";
RB1.GroupName = "bla";
RB1.CheckedChanged += new EventHandler(CheckedChanged);
RadioButton RB2 = new RadioButton();
RB2.ID = "2";
RB2.GroupName = "bla";
RB2.CheckedChanged += new EventHandler(CheckedChanged);
PlaceHolder1.Controls.Add(RB1);
PlaceHolder1.Controls.Add(RB2);
}
protected void CheckedChanged(object sender, EventArgs e)
{
Label1.Text = ((RadioButton)sender).ID;
}
In my project I have dynamic creating of RadioButtons (the number of rows I get from database). The same adding eventHandler does not work, but if I write
MyRadioButton.Load += new EventHandler(Another_method);
The Another_method will start, but in
MyRadioButton.CheckedChanged += new EventHandler(Main_method);
the Main_method will not start if I choose one of the RadioButtons.
What is wrong?
#KevinP
This is my code:
Table tb1 = new Table();
PlaceHolder1.Controls.Add(tb1);
TableRow tr = new TableRow();
TableCell tc = new TableCell();
//adding the first row with title"
tr.Cells.Add(tc);
for (int i = 0; i < ((ArrayList)(result[0])).Count; i++)
{
tc = new TableCell();
Label example = new Label();
example.Text = ((columnsResultFromSqlClients)(i)).ToString();
tc.Controls.Add(example);
tr.Cells.Add(tc);
}
tb1.Rows.Add(tr);
//filling the table
for (int i = 0; i < result.Count; i++)
{
tr = new TableRow();
tc = new TableCell();
//adding radio button
RadioButton RB = new RadioButton();
RB.Attributes.Add("value", ((ArrayList)(result[i]))[0].ToString());
RB.GroupName = "for_selecting";
RB.ID = ((ArrayList)(result[i]))[0].ToString();
RB.CheckedChanged += new EventHandler(RB_CheckedChanged2);
//RB.AutoPostBack = true;
RB.Attributes.Add("AutoPostBack", "True");
tc.Controls.Add(RB);
tr.Cells.Add(tc);
//adding content
for (int j = 0; j < ((ArrayList)(result[i])).Count; j++)
{
tc = new TableCell();
Label example = new Label();
example.Text = ((ArrayList)(result[i]))[j].ToString();
tc.Controls.Add(example);
tr.Cells.Add(tc);
}
tb1.Rows.Add(tr);
}
If I use RB.AutoPostBack = true;, I have no time to press the button to submit my choice, cause the page will reload when i click the one of the Radio Buttons.
Also the RB_CheckedChanged2 code:
protected void RB_CheckedChanged2(object sender, EventArgs e)
{
RadioButton tempRB = (RadioButton)sender;
if (tempRB.Checked)
{
selected_id = tempRB.ID;
}
}
The select_id is a static int varible with standart value = "-1".
If I am not mistaken, with dynamic controls in ASP.Net, you need to "rewire" their events on a postback. Remember that on a postback, dynamic controls are no longer there. You have to recreate them.

Categories