Cannot fire runtime radiobutton checkedchanged event inside linkbutton click event - c#

I am trying to fire radiobutton checked changed event on linkbutton click event but instead it goes to the page load and the radiobutton checkedchanged event does not fires.
protected void Page_Load(object sender, EventArgs e)
{
string Query = "select Q101004,Q101005 from Q101 where Q101001<110000013";
DataTable dt = ExecuteDataset(Query).Tables[0];
ViewState["dt"] = dt;
Table t = new Table();
TableRow r = new TableRow();
t.Rows.Add(r);
TableCell c = new TableCell();
lnkbtn = new LinkButton();
r.Cells.Add(c);
lnkbtn.Text = "Click Here";
lnkbtn.Visible = true;
lnkbtn.CommandName = "Test";
lnkbtn.CommandArgument = "Hi";
lnkbtn.ID = "Hi";
PlaceHolder2.Controls.Add(lnkbtn);
for (int i = 0; i < dt.Rows.Count; i++)
{
rb = new RadioButton();
rb.AutoPostBack = true;
rb.ID = "m" +i;
rb.GroupName = "a";
rb.Text = dt.Rows[0][0].ToString();
CbxList = new CheckBoxList();
CbxList.ID = "Cbx"+i;
CbxList.Enabled = false;
CbxList.RepeatDirection = RepeatDirection.Horizontal;
CbxList.RepeatColumns = 2;
CbxList.CellPadding = 10;
CbxList.CellSpacing = 5;
CbxList.RepeatLayout = RepeatLayout.Table;
options = dt.Rows[0][1].ToString().Split('~');
PlaceHolder2.Controls.Add(new LiteralControl("<br/>"));
for (int j = 0; j < options.Length; j++)
{
CbxList.Items.Add(new ListItem(options[j], options[j]));
}
PlaceHolder2.Controls.Add(rb);
PlaceHolder2.Controls.Add(CbxList);
if (i ==0)
rb.CheckedChanged += new EventHandler(rb_CheckedChanged);
else
lnkbtn.Click += new EventHandler(lnkbtn_Click);
}
}
void lnkbtn_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)ViewState["dt"];
lnkbtn = (LinkButton)PlaceHolder2.FindControl("Hi");
string str=((LinkButton)sender).CommandArgument;
//lnkbtn.Enabled = true;
if (lnkbtn.ID == str)
{
rb = new RadioButton();
rb.AutoPostBack = true;
rb.ID = "m";
rb.GroupName = "a";
rb.Text = dt.Rows[0][0].ToString();
CbxList = new CheckBoxList();
CbxList.ID = "Cbx";
CbxList.Enabled = false;
CbxList.RepeatDirection = RepeatDirection.Horizontal;
CbxList.RepeatColumns = 2;
CbxList.CellPadding = 10;
CbxList.CellSpacing = 5;
CbxList.RepeatLayout = RepeatLayout.Table;
options = dt.Rows[0][1].ToString().Split('~');
PlaceHolder2.Controls.Add(new LiteralControl("<br/>"));
for (int i = 0; i < options.Length; i++)
{
CbxList.Items.Add(new ListItem(options[i], options[i]));
}
PlaceHolder2.Controls.Add(rb);
PlaceHolder2.Controls.Add(CbxList);
if (lnkbtn.CommandName == "Test")
{
rb.CheckedChanged += new EventHandler(rb_CheckedChanged);
}
}
}

Your code subscribes to the checked changed but does not invoke it.
If you want to do this, you could call the rb_CheckedChanged() method directly.

hope this helps....its working fine for me.
Just Modify your code with this code and You will be able to achieve your desired output
private void InitPage()
{
string a1, b,a2,b2;
_objSession = (ClsSession)Session["Login"];
ds = _objSession._DataSet;
dtAll = ds.Tables[3];
dr = dtAll.NewRow();
string str2 = (string)ViewState["str1"];
if (str2 != null)
{
string[] str3 = str2.Split('~');
a2 = str3[0];
b2 = str3[1];
}
else
{
a2 = "a0";
b2 = "b0";
}
str = (string)ViewState["str"];
if (str == null)
{
a1 = "a0";
b = "b";
}
else
{
string[] str1 = str.Split('~');
a1 = str1[0];
b = str1[1];
}
if (str==null)
{
for (int j = 0; j < dtAll.Rows.Count; j++)
{
Table t = new Table();
TableRow r = new TableRow();
t.Rows.Add(r);
TableCell c = new TableCell();
lnkbtn = new LinkButton();
r.Cells.Add(c);
lnkbtn.Text = (j + 1).ToString();
lnkbtn.Visible = true;
lnkbtn.CommandName = "Test";
lnkbtn.CommandArgument = "Hi" + j;
lnkbtn.ID = "Hi" + j;
lnkbtn.ForeColor = Color.Blue;
lnkbtn.Width = 30;
lnkbtn.Font.Bold = true;
lnkbtn.Font.Size = 14;
lnkbtn.Font.Underline = false;
lnkbtn.Click += new EventHandler(lnkbtn_Click);
c.Controls.Add(lnkbtn);
plcHdrLinkButton.Controls.Add(lnkbtn);
}
ViewState["a"] = 0;
}
if (str2 != null)
{
string[] str3 = str2.Split('~');
a2 = str3[0];
a1 = a2;
}
string resultString = Regex.Match(a1, #"\d+").Value;
int a = int.Parse(resultString);
ViewState["a"] = a;
plcHdrQuestion.Controls.Clear();
rb = new RadioButton();
rb.ID = "m" + a;
rb.AutoPostBack = true;
rb.GroupName = "a";
rb.Text = (a + 1) + "." + " " + dtAll.Rows[a][4].ToString();
CbxList = new CheckBoxList();
CbxList.ID = "Cbx" + a;
CbxList.Enabled = false;
CbxList.RepeatDirection = RepeatDirection.Horizontal;
CbxList.RepeatColumns = 2;
CbxList.CellPadding = 10;
CbxList.CellSpacing = 5;
CbxList.RepeatLayout = RepeatLayout.Table;
options = dtAll.Rows[a][5].ToString().Split('~');
plcHdrQuestion.Controls.Add(new LiteralControl("<br/>"));
for (int i = 0; i < options.Length; i++)
{
CbxList.Items.Add(new ListItem(options[i], options[i]));
}
plcHdrQuestion.Controls.Add(rb);
plcHdrQuestion.Controls.Add(CbxList);
rb.CheckedChanged += new EventHandler(lnkbtn_Click);
string st = (string)ViewState["str"];
ViewState["str1"] = st;
ViewState["str"] = null;
}
protected void lnkbtn_Click(object sender, EventArgs e)
{
Boolean _flag=true;
ds = _objSession._DataSet;
dt1 = ds.Tables[3];
dr = dt1.NewRow();
StringBuilder sb=new StringBuilder ();
for (int i = 0; i < dt1.Rows.Count; i++)
{
Cbx = (RadioButton)plcHdrQuestion.FindControl("m" + i);
Cbx1 = (CheckBoxList)plcHdrQuestion.FindControl("Cbx" + i);
if (Cbx != null)
{
if (Cbx.Checked == true)
{
Cbx1.Enabled = true;
_flag = false;
string st1 = (string)ViewState["st"];
string st="c";
if (st1 != null)
st = st1 + "~" + st;
ViewState["st"] = st;
st1 = (string)ViewState["st"];
sb.Append(st);
}
break;
}
}
int count=(sb.ToString().Count());
if (count>2)
{
_flag = true;
}
if ((lnkbtn.CommandName == "Test") && (_flag ==true))
{
for (int j = 0; j < dt1.Rows.Count; j++)
{
lnkbtn = (LinkButton)plcHdrLinkButton.FindControl("Hi" + j);
string str = ((LinkButton)sender).CommandArgument;
lnkbtn.Enabled = true;
if (lnkbtn.ID == str)
{
ViewState["str"] = str + "~" + lnkbtn.ID;
InitPage();
ViewState["st"] = null;
_flag = false;
break;
}
}
}
}

You need to read up on your ASP.NET Page Life Cycle - http://msdn.microsoft.com/en-us/library/ms178472(VS.100).aspx
Very roughly, the following events get called during page lifecycle.
Init -> Controls are created & wired up with event handlers
Load ViewState/ControlState -> Controls are reset to their previous state from the last round trip (including whether or not they need to fire their events)
Load -> Controls are loaded into the Page's Control Tree
Control Events (Clicks etc...) are executed.
The problem you have is that you are creating your control and wiring it up to fire dynamically in the 4th step there, which is too late in the page lifecycle.
On the next round trip, if someone does interact with that control, and the lifecycle starts over, that control won't exist by the time the page is preparing to execute commands.
You'll need to move the creation of your RadioButton to a much earlier stage in the pages creation. In your updated code, try moving your Page_Load code into the override oninit method instead.

Related

how to create dynamic button in c# windows application

i have two layutflowpanel
1-flowpanel_category
2-flowpanel_products
when i use nested for loop inside button click to get products from current select category another flowpanel_prd not showing that products from categorey maybe i have some mistake in the some point
i set inside InitialComponents this code to retrive all items from category to put it inside flowpanel_category
//get all category and set it all to flowpanel_cat
FLOWPANEL_CAT.Controls.Clear();
try
{
DT = clsgetcat.get_prd_categories();
for (int i = 0; i <= DT.Rows.Count; i++)
{
Extendedbutton Eb = new Extendedbutton();//with Extendedbutton this time
Eb.prdid = DT.Rows[i][0].ToString();//this asigns product_id to extended txtprdid
Eb._prdnme = DT.Rows[i][1].ToString();//this asigns product_nme to extended txtprdnme
Eb._myval = DT.Rows[i][1].ToString();//this asigns products to extended buttondescription
Eb.Name = DT.Rows[i][1].ToString();
Eb.Text = DT.Rows[i][1].ToString();
Eb.ForeColor = Color.White;
Eb.BackColor = Color.SkyBlue;
Eb.Font = new Font("Serif", 10, FontStyle.Regular);
Eb.Width = 100;
Eb.Height = 60;
Eb.TextAlign = ContentAlignment.MiddleCenter;
Eb.Margin = new Padding(5);
Button b = addbutton(i);
Eb.Click += new System.EventHandler(this.buttonclick);
FLOWPANEL_CAT.Controls.Add(Eb);
}
}
catch
{
return;
}
iset inside buttonclick this code to show each items from category inside flowpanel_prodcuts
public void buttonclick(object sender, EventArgs e)
{
FLOWPANEL_PRD.Controls.Clear();
for (int i = 0; i <= DT.Rows.Count; i++)
{
try
{
for (int j = 0; j <= i; j++)
{
Extendedbutton Eb = new Extendedbutton();//with Extendedbutton this time
Eb._prdid = DT.Columns[0].ToString();
string prdid = ((Extendedbutton)sender)._prdid;
Eb._prdnme = DT.Columns[1].ToString();
string prdnme = ((Extendedbutton)sender)._prdnme;
Eb.Name = DT.Rows[j][1].ToString();
Eb.Text = DT.Rows[j][1].ToString();
Eb.ForeColor = Color.White;
Eb.BackColor = Color.SkyBlue;
Eb.Font = new Font("Serif", 10, FontStyle.Regular);
Eb.Width = 100;
Eb.Height = 60;
Eb.TextAlign = ContentAlignment.MiddleCenter;
Eb.Margin = new Padding(5);
Button b = addbutton(j);
Eb.Click += new System.EventHandler(this.buttonclick);
txttotalamount.Clear();
txtprdqty.Clear();
txtprdqty.Focus();
FLOWPANEL_PRD.Controls.Add(Eb);
}
}
catch
{
return;
}
}
txtprdqty.Focus();
}
Button addbutton(int i)
{
Extendedbutton EB = new Extendedbutton();
EB.Name = EB._myval;
EB.Text = EB._myval;
EB.ForeColor = Color.White;
EB.BackColor = Color.SkyBlue;
EB.Font = new Font("Serif", 10, FontStyle.Regular);
EB.Width = 100;
EB.Height = 60;
EB.TextAlign = ContentAlignment.MiddleCenter;
EB.Margin = new Padding(5);
return EB;
}
this picture show you output result but i have some mistake when i get products from each category

How to get the values of button templatefield in Gridview?

I want to display the row details of Gridview when user click the button of template field. I got the output to display the button in a Gridview using template field. But when user click the button it reload the page and display the empty template with rows.
Full Coding of c#
string selectedColumn;
string[] splitSelectedColumn;
string groupByColumn;
string[] splitGroupByColumn;
ArrayList listBtnOrLbl = new ArrayList();
int compareFlag = 0;
protected void btnRefresh_Click(object sender, EventArgs e)
{
selectedColumn = txtColumnNames.Text;
splitSelectedColumn = selectedColumn.Split(',');
groupByColumn = txtGroupBy.Text;
splitGroupByColumn = groupByColumn.Split(',');
string[] compareGroup = new string[splitGroupByColumn.Length];
//Grouping column names using selected column text
int flag = 1;
foreach (string columnName in splitSelectedColumn)
{
flag = 1;
foreach (string groupByName in splitGroupByColumn)
{
if (columnName.Equals(groupByName))
{
flag = 2;
break;
}
}
if (flag == 1)
{
groupByColumn = groupByColumn + "," + columnName;
}
}
// CREATE A TEMPLATE FIELD AND BOUND FIELD
BoundField bfield = new BoundField();
TemplateField[] ttfield = new TemplateField[splitGroupByColumn.Length];
for (int i = 0; i < splitSelectedColumn.Length; i++)
{
if (i < splitGroupByColumn.Length)
{
ttfield[i] = new TemplateField();
ttfield[i].HeaderText = splitGroupByColumn[i];
GridView1.Columns.Add(ttfield[i]);
}
else
{
try
{
bfield.HeaderText = splitSelectedColumn[i];
bfield.DataField = splitSelectedColumn[i];
Response.Write("<br/>BOUND FIELD==" + splitGroupByColumn[i]);
GridView1.Columns.Add(bfield);
}
catch (Exception)
{
}
}
}
// CREATE DATA TABLE and COLUMN NAMES
DataTable dt = new DataTable();
//dt.Columns.Clear();
for (int i = 0; i < splitSelectedColumn.Length; i++)
{
dt.Columns.Add(splitSelectedColumn[i]);
//Console.WriteLine(splitSelectedColumn[i]);
System.Diagnostics.Debug.WriteLine(splitSelectedColumn[i]);
Response.Write("<br/>DT COLUMN NAMES==" + splitSelectedColumn[i]);
}
//ADD ROWS FROM DATABASE
string cs = ConfigurationManager.ConnectionStrings["connectionStringDB"].ConnectionString;
//int compareFlag = 0;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
//cmd.CommandText = "select " + selectedColumn + " FROM [RMSDemo].[dbo].[ItemRelation] where ItemLookupCode='" + txtItemLookupCode.Text + "'and ChildItemLookupCode1='" + txtChildItemLookupCode.Text + "' group by " + groupByColumn + " ";
cmd.CommandText = "select " + selectedColumn + " FROM [RMSDemo].[dbo].[ItemRelation] group by " + groupByColumn + " ";
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
string addData = string.Empty;
string[] stackss = new string[splitSelectedColumn.Length];
while (rd.Read())
{
//SET the FIRST VALUES in `stackss[]` for comparing next values of rd[]
if (compareFlag == 0)
{
for (int i = 0; i < splitGroupByColumn.Length; i++)
{
compareGroup[i] = rd[splitGroupByColumn[i]].ToString();
Response.Write("<br/>COMPARE GROUP [i]==" + compareGroup[i]);
}
compareFlag = 1;
Response.Write("<br/>splitSelectedColumn.LENGTH==" + splitSelectedColumn.Length);
Response.Write("<br/>STACK.LENGTH==" + stackss.Length);
for (int i = 0; i < stackss.Length; i++)
{
stackss[i] = "";
}
for (int i = 0; i < compareGroup.Length; i++)
{
stackss[i] = compareGroup[i];
}
//TESTING PURPOSE ONLY
for (int i = 0; i < stackss.Length; i++)
{
//stack[i] = "";
Response.Write("<br/>STACK.VALUES==" + stackss[i]);
}
var row = dt.NewRow();
DataRowCollection drc = dt.Rows;
DataRow rowss = drc.Add(stackss);
Response.Write("Execute BUTTON");
listBtnOrLbl.Add("button");
}
//stackss = new string[] { "" };
for (int i = 0; i < stackss.Length; i++)
{
stackss[i] = "";
}
int tempValue = 0;
for (int i = 0; i < compareGroup.Length; i++)
{
if (compareGroup[i] == rd[i].ToString())
{
tempValue = tempValue + 1;
if (tempValue == compareGroup.Length)
{
for (int k = 0; k < splitSelectedColumn.Length; k++)
{
stackss[k] = rd[k].ToString();
Response.Write("second rowsssss ==== " + stackss[k]);
if (k + 1 == splitSelectedColumn.Length)
{
var row = dt.NewRow();
DataRowCollection drc = dt.Rows;
DataRow rowss = drc.Add(stackss);
Response.Write("compare flag checking");
Response.Write("Execute LABEL");
listBtnOrLbl.Add("label");
compareFlag = 0;
}
}
}
}
}
//GridView1.DataSource = dt;
//GridView1.DataBind();
}
rd.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Gridview templatefield will generate when user click Refresh button. The above coding is that one to generate column and templatefield
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Response.Write("<br/>compare flag checking OVER button count=======================" + listBtnOrLbl.Count);
if (e.Row.RowType == DataControlRowType.DataRow)
{
int size = splitGroupByColumn.Length;
//Button[] lnkBtn = new Button[size];
Label[] lblData = new Label[size];
Response.Write("<br/>Inside button count=======================" + listBtnOrLbl.Count);
if ("button".Equals(listBtnOrLbl[j]))
{
for (int i = 0; i < splitGroupByColumn.Length; i++)
{
Button lnkView = new Button();
lnkView.ID = "lnkView";
lnkView.Text = (e.Row.DataItem as DataRowView).Row[splitGroupByColumn[i]].ToString();
//lnkView.Text = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row[splitGroupByColumn[i]].ToString();
e.Row.Cells[i].Controls.Add(lnkView);
}
j++;
}
else
{
for (int i = 0; i < splitGroupByColumn.Length; i++)
{
lblData[i] = new Label();
lblData[i].ID = "lblView";
lblData[i].Text = (e.Row.DataItem as DataRowView).Row[splitGroupByColumn[i]].ToString();
Response.Write("<br/>PRINT label==" + lblData[i].Text);
e.Row.Cells[i].Controls.Add(lblData[i]);
//e.Row.Visible = false;
}
j++;
}
}
protected void ViewDetails(object sender, EventArgs e)
{
Response.Redirect("exit.aspx"); //for testing purpose I gave like this, But this method is not calling i think when user clicks button
Response.Write("testing....");
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('TESTING:')", true);
}
Output before user clicks the Button
output1
After clicks the button(first button)
output2
I already did like this before,but that was small one not more complex code like this. that was working fine. Now What i did wrong here?.
Thanks
I think ViewDetails() method is not calling when user clicks the button

Dynamically created controls in Page_Load()

I have a question regarding creating controls in runtime in ASP.NET 4.0. I'm building a application and in admin.aspx page I have multiple controls (DropDownLists) which are dynamically created with values from a Sql database.
I know that for having events fired for dynamically created controls, I have to create this controls in Page_Load() or in Page_Init().
My project has a Master Page, in which I have a 1 second timer which updates a clock. This timer event calls my admin.aspx Page_Load() function, so my method which creates dynamic controls it's called every 1 second - connection to database is made every one second, please look below to my code.
It's a good practice to do that? Can you please propose some ideas?
protected void Page_Load(object sender, EventArgs e)
{
_SinopticBackgroundColor = ConfigurationManager.AppSettings["SinopticBackgroundColor"];
panelContent.Style.Add("background-color", _SinopticBackgroundColor);
Control c = GetControlThatCausedPostBack(this);
if (c != null)
{
if (c.ID.Equals("btnManageCategory"))
hfPageManage.Value = "category";
else if (c.ID.Equals("btnManageDevices"))
hfPageManage.Value = "device";
}
if (hfPageManage.Value.Equals("category"))
{
cbTreeViewGroup.Visible = false;
UpdateSinopticCategoryManager(TreeView1.SelectedNode); //this is the functions which loads controls from database..
}
else if (hfPageManage.Value.Equals("device"))
{
cbTreeViewGroup.Visible = true;
}
else
{
cbTreeViewGroup.Visible = false;
}
if (!Page.IsPostBack)
{
LoadFunctions(); // loads some values from database into datatables
}
else
{
}
}
And here is the functions which creates controls
private void UpdateSinopticCategoryManager(TreeNode node = null)
{
if (node == null)
return;
DataTable categoriiDT = null;
using (var connection = new SqlConnection(Database.ConnectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM categories WHERE CategoryID = #CategoryID";
command.Parameters.Add("CategoryID", node.Value);
SqlDataAdapter ad = new SqlDataAdapter(command);
DataSet ds = new DataSet("CATEGORYPROPERTIES");
connection.Open();
ad.Fill(ds);
// verificam sa avem date
if (ds.Tables.Count <= 0)
return;
if (ds.Tables[0].Rows.Count <= 0)
return;
categoriiDT = ds.Tables[0];
}
}
// generate table
Table table = new Table();
table.Style.Add("position", "relative");
table.Style.Add("top", "20px");
table.Style.Add("margin-left", "20px");
table.BorderStyle = BorderStyle.Solid;
table.BorderWidth = 1;
// header
TableHeaderRow hr = new TableHeaderRow();
for (int i = 0; i < 2; i++)
{
TableHeaderCell hc = new TableHeaderCell();
if (i > 0)
{
hc.Text = "FUNCTION";
//hc.Width = 200;
}
else
{
hc.Width = 100;
}
hr.Cells.Add(hc);
}
table.Rows.Add(hr);
var inputs = (from a in categoriiDT.Columns.Cast<DataColumn>()
where a.ColumnName.ToLowerInvariant().Contains("input")
select a.ColumnName).ToArray();
if (inputs.Count() <= 0)
return;
//rows input
for (int i = 0; i < inputs.Count(); i++)
{
TableRow tableRow = new TableRow();
for (int j = 0; j < 2; j++)
{
TableCell cell = new TableCell();
if (j > 0)
{
// adaugare 2 dropdownlist
DropDownList categList = new DropDownList();
categList.SelectedIndexChanged += new EventHandler(categList_SelectedIndexChanged);
foreach (DataRow row in functionsCategories.Rows)
{
categList.Items.Add(new ListItem(row["FunctionCategoryName"].ToString(), row["FunctionCategoryID"].ToString()));
}
DropDownList funcList = new DropDownList();
int selF = 0, selC = 0;
for (int fi = 0; fi < functions.Rows.Count; fi++)// (DataRow row in functions.Rows)
{
funcList.Items.Add(new ListItem(functions.Rows[fi]["FunctionName"].ToString(), functions.Rows[fi]["FunctionID"].ToString()));
if (functions.Rows[fi]["FunctionID"].ToString() == categoriiDT.Rows[0][inputs[i]].ToString())
{
selF = fi;
selC = Int32.Parse(functions.Rows[fi]["FunctionCategoryID"].ToString());
}
}
funcList.SelectedIndex = selF;
categList.SelectedIndex = functionsCategories.Rows.IndexOf(
(from c in functionsCategories.AsEnumerable()
where c["FunctionCategoryID"].ToString().Equals(selC.ToString())
select c).FirstOrDefault());
cell.Controls.Add(categList);
cell.Controls.Add(funcList);
}
else
{
Label label = new Label();
label.Text = "INPUT " + i.ToString();
label.Style.Add("font-weight", "bold");
cell.Controls.Add(label);
}
tableRow.Cells.Add(cell);
}
table.Rows.Add(tableRow);
}
//rows output
for (int i = 0; i < 4; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < 2; j++)
{
TableCell cell = new TableCell();
if (j > 0)
{
DropDownList list = new DropDownList();
list.Width = 200;
list.Items.AddRange(GetOutputFunctions());
list.BorderColor = Color.Goldenrod;
cell.Controls.Add(list);
}
else
{
Label label = new Label();
label.Text = "OUTPUT " + i.ToString();
label.Style.Add("font-weight", "bold");
cell.Controls.Add(label);
}
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
// add table to panel
panelContent.Controls.Add(table);
}
It's about this: DropDownList categList = new DropDownList();
This may get answered more quickly and effectively in codereview https://codereview.stackexchange.com/

How can I get ID's of Dynamically generated Controls?

Hiiii,
In the following image the table & controls in it are generated dynamically.
Table is created onclick of "create table" button using values from dropdownlist which has no. of rows as values.
How can I get particular “Fileupload” & “Upload” button’s ID.
On click of “upload” button only fileupload control in same row as of that button should be accessed & it should not loop through all the fileupload controls in the table.
In my code, when I click Upload button in lower rows(say 3rd row) then it uploads the file selected in upper fileupload controls( here 1st n 2nd row along with 3rd row ) also.
I don’t want this. I just want to upload file from filupload control in the same row of clicked button.
CODE :
public partial class stable : System.Web.UI.Page
{
private int tblRow;
private int tblCol = 9;
private int i, j;
private bool CTflag;
Table table = new Table();
TableRow row,rrow;
TableCell cell,rcell;
FileUpload fileUp;
Button UpLdButton;
Button btnCal;
TextBox tb;
Label tbr;
string cmdArg; // for passing filuploaders id with Command button
private string filename = "fileUpLoader";
private string tbRowId = "row";
private string tbColId = "col";
protected int Rows
{
get
{
return ViewState["Rows"] != null ? (int)ViewState["Rows"] : 0;
}
set
{
ViewState["Rows"] = tblRow;
}
}
// Columns property to hold the Columns in the ViewState
protected int Columns
{
get
{
return ViewState["Columns"] != null ? (int)ViewState["Columns"] : 0;
}
set
{
ViewState["Columns"] = tblCol;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (CTflag == false)
{
this.Rows = tblRow;
this.Columns = tblCol;
CreateDynamicTable();
}
else
{
CTflag = true;
}
}
//LoadViewState(object this);
//CreateDynamicTable();
}
protected void Button1_Click(object sender, EventArgs e)
{
clrControls();
CreateDynamicTable();
}
protected void CreateDynamicTable()
{
tblRow = Convert.ToInt32(DropDownList1.SelectedValue);
//Creat the Table and Add it to the Page
if (CTflag == false)
{
table.Caption = "Challan Entry";
table.ID = "Challan Entry";
table.BackColor = System.Drawing.Color.BurlyWood;
Page.Form.Controls.Add(table);
// Now iterate through the table and add your controls
for (i = 0; i < 1; i++)
{
row = new TableRow();
row.BorderStyle = BorderStyle.Ridge;
for (j = 0; j <= tblCol; j++)
{
cell = new TableCell();
cell.BorderWidth = 5;
cell.BorderStyle = BorderStyle.Ridge;
cell.BorderColor = System.Drawing.Color.Azure;
for (j = 0; j <= tblCol; j++)
{
string[] Header = { "CC NO.", "DATE", "TotalAmt", "NoOfRecpt", "Energy", "New", "Theft", "Misc", "SelectFile", "Upload", "Status" };
Label lbl = new Label();
lbl.ID = "lblHeader" + j;
if (j == 8)
{
lbl.Width = 220;
}
else if (j == 9)
{
lbl.Width = 50;
}
else
{
lbl.Width = 100;
}
lbl.Text = Header[j];
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
row.Cells.Add(cell);
}
// Add the TableRow to the Table
table.Rows.Add(row);
}
for (i = 0; i < tblRow; i++)
{
row = new TableRow();
row.ID = tbRowId + i;
row.BorderStyle = BorderStyle.Ridge;
for (j = 0; j <= tblCol; j++)
{
cell = new TableCell();
cell.ID = tbColId + i + j;
cell.BorderWidth = 5;
cell.BorderStyle = BorderStyle.Ridge;
cell.BorderColor = System.Drawing.Color.Azure;
for (j = 0; j <= 0; j++)
{
Label lbl = new Label();
lbl.ID = "lblCCRow" + i + "Col" + j;
lbl.Text = "CC NO. " + i + " ";
lbl.Width = 100;
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (j = 1; j <= 1; j++)
{
Label lbl = new Label();
lbl.ID = "lblRow" + i + "Col" + j;
lbl.Width = 100;
lbl.Text = Convert.ToString(DateTime.Now.Day) + "/" + Convert.ToString(DateTime.Now.Month) + "/" + Convert.ToString(DateTime.Now.Year);
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (j = 2; j <= 7; j++)
{
tb = new TextBox();
tb.Width = 100;
tb.ID = "txtBoxRow" + i + "Col" + j;
//txtbxNames[i,j] = Convert.ToString(tb.ID);
tb.Text = "0";
// Add the control to the TableCell
cell.Controls.Add(tb);
}
for (j = 8; j <= 8; j++)
{
fileUp = new FileUpload();
//m = i; n = j;
fileUp.ID = filename + i + j;
fileUp.Width = 220;
cell.Controls.Add(fileUp);
cmdArg = fileUp.ID;
UpLdButton = new Button();
UpLdButton.Width = 100;
UpLdButton.Text = "Upload" + i + j;
UpLdButton.ID = UpLdButton.Text;
UpLdButton.CommandArgument= cmdArg;
cell.Controls.Add(UpLdButton);
UpLdButton.Click += new EventHandler(UpLdButton_Click);
}
for (j = 9; j <= 9; j++)
{
Label lbl = new Label();
lbl.ID = "lblRow" + i + j;
lbl.Text = "[ Status ]";
lbl.Width = 100;
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
row.Cells.Add(cell);
}
// Add the TableRow to the Table
table.Rows.Add(row);
} //outer for-loop end
for (i = 0; i < 1; i++)
{
rrow = new TableRow();
rrow.ID = "ResultRow";
rrow.BorderStyle = BorderStyle.Ridge;
for (j = 0; j <= tblCol; j++)
{
rcell = new TableCell();
rcell.ID = "resultCol" + j;
rcell.BorderWidth = 5;
rcell.BorderStyle = BorderStyle.Ridge;
rcell.BorderColor = System.Drawing.Color.Azure;
for (j = 0; j <= 0; j++)
{
Label lbl = new Label();
//lbl.ID = "lblCCRow" + i + "Col" + j;
lbl.Text = "<b>Total</b>";
lbl.Width = 100;
// Add the control to the TableCell
rcell.Controls.Add(lbl);
}
for (j = 1; j <= 1; j++)
{
Label lbl = new Label();
//lbl.ID = "lblRow" + i + "Col" + j;
lbl.Width = 100;
lbl.Text = Convert.ToString(DateTime.Now.Day) + "/" + Convert.ToString(DateTime.Now.Month) + "/" + Convert.ToString(DateTime.Now.Year);
// Add the control to the TableCell
rcell.Controls.Add(lbl);
}
for (j = 2; j <= 7; j++)
{
tbr = new Label();
tbr.Width = 100;
tbr.ID = "txtResult" +i+j;
tbr.Text = tbr.ID;
tbr.EnableTheming = true;
tbr.BackColor = System.Drawing.Color.White;
//txtResNames[i, j] = Convert.ToString(tbr.ID);
// Add the control to the TableCell
rcell.Controls.Add(tbr);
}
for (j = 8; j <= 8; j++)
{
btnCal = new Button();
btnCal.Width = 100;
btnCal.Text = "Calculate";
btnCal.ID = btnCal.Text;
rcell.Controls.Add(btnCal);
btnCal.Click += new EventHandler(btnCal_Click);
}
rrow.Cells.Add(rcell);
}
// Add the TableRow to the Table
table.Rows.Add(rrow);
}
//flag seetting
CTflag = true;
ViewState["dynamictable"] = true;
}
}
void btnCal_Click(object sender, EventArgs e)
{
TextBox tbres = new TextBox();
TextBox tbTemp = new TextBox();
double TotAmt = 0, NoofRect = 0, Energy = 0,New1 = 0, Theft = 0, Misc = 0;
for (int i = 0; i < tblRow; i++)
{
for (int j = 2; j <= 7; j++)
{
TextBox tb = (TextBox)FindControlRecursive(this, string.Format("txtBoxRow{0}Col{1}", i, j));
Label tbr = (Label)FindControlRecursive(this, string.Format("txtResult{0}{1}", 0, j));
switch (j)
{
case 2:
TotAmt += Convert.ToDouble(tb.Text);
Label1.Text = Convert.ToString(TotAmt);
tbr.Text = Convert.ToString(TotAmt);
break;
case 3:
NoofRect += Convert.ToDouble(tb.Text);
//Label1.Text = Convert.ToString(NoofRect);
tbr.Text = Convert.ToString(NoofRect);
break;
case 4:
Energy+= Convert.ToDouble(tb.Text);
//Label1.Text = Convert.ToString(TotAmt);
tbr.Text = Convert.ToString(Energy);
break;
case 5:
New1+= Convert.ToDouble(tb.Text);
//Label1.Text = Convert.ToString(TotAmt);
tbr.Text = Convert.ToString(New1);
break;
case 6:
Theft+= Convert.ToDouble(tb.Text);
//Label1.Text = Convert.ToString(TotAmt);
tbr.Text = Convert.ToString(Theft);
break;
case 7:
Misc+= Convert.ToDouble(tb.Text);
//Label1.Text = Convert.ToString(TotAmt);
tbr.Text = Convert.ToString(Misc);
break;
}
}
}
}
protected void clrControls()
{
Label1.Text = "";
for (int i = 0; i < tblRow; i++)
{
for (int j = 2; j <= 7; j++)
{
fileUp = (FileUpload)FindControlRecursive(this, string.Format("fileUpLoader{0}{1}", i, 8));
fileUp.Enabled = true;
Button btn = (Button)FindControlRecursive(this, string.Format("Upload{0}{1}", i, 8));
btn.Enabled=true;
TextBox tb = (TextBox)FindControlRecursive(this, string.Format("txtBoxRow{0}Col{1}", i, j));
tb.Text = "0";
Label tbr = (Label)FindControlRecursive(this, string.Format("txtResult{0}{1}", 0, j));
tbr.Text = "0";
Label statlbl = new Label();
statlbl = (Label)FindControlRecursive(this, string.Format("lblRow{0}{1}", i, 9));
statlbl.Text = "[status]";
}
}
for (i = 0; i < 1; i++)
{
for (j = 8; j <= 8; j++)
{
btnCal.Enabled = true;
}
}
}
protected override void LoadViewState(object earlierState)
{
base.LoadViewState(earlierState);
if (ViewState["dynamictable"] == null)
{
CreateDynamicTable();
}
}
void UpLdButton_Click(object sender, EventArgs e)
{
Button btnUpLD = sender as Button;
for (int i = 0; i < tblRow; i++)
{
Button tb = (Button)FindControlRecursive(this, string.Format("Upload{0}{1}", i, 8));
fileUp = (FileUpload)FindControlRecursive(this, string.Format("fileUpLoader{0}{1}", i, 8));
Label statlbl = new Label();
statlbl = (Label)FindControlRecursive(this, string.Format("lblRow{0}{1}", i, 9));
if (!fileUp.HasFile)
{
//statlbl.Text = "[status]";
continue;
}
else
{
UploadFile(fileUp,tb);
if (tb.Enabled == true && fileUp.Enabled == true)
{
statlbl.Text = "[status]";
}
else
{
statlbl.Text = "Uploaded";
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
protected void UploadFile(FileUpload xyz, Button btn)
{
if (xyz.HasFile)
{
string extension = System.IO.Path.GetExtension(xyz.FileName);
if (extension == ".dat" || extension == ".B60")
{
if (File.Exists(Server.MapPath("~\\") + xyz.FileName))
{
Label1.Text = "File " + xyz.FileName + " Already Exists!";
}
else
{
xyz.PostedFile.SaveAs(Server.MapPath("~\\") + xyz.FileName);
Label1.Text = "The " + xyz.FileName + " Has been uploaded";
btn.Enabled = false;
xyz.Enabled = false;
}
}
else
{
Label1.Text = "* You can select only '.dat' & '.B60' type files";
btn.Enabled = true;
xyz.Enabled = true;
}
}
else
{
Label1.Text = "Select a file";
}
}
}
plz Help me Out !!!
Thanx in Advance...
why not store a Row ID in the command argument for the button and then when the button is click you can use this to loop through all the rows untill the id matchs the row you are looking for, for example
foreach (DateRow test in table.Rows)
if ((test.findcontrol(uploadbutton) as Button).commandArgument = (Sender as Button).commandArgumrnt
{
//do stuff here
}
else
{
\\ do nothing
}
Hope this helps

How to get the values dynamically added controls in other parts of the code?

I have a method that creates textboxes depending on the number of parameters values that the user has to enter.And its working fine. The problem is that when the user clicks Ok i want to take the value that the user entered in these textboxes and replace them in a string. When am searching these textboxes to get the text value from them am not finding them. How do i get these values to continue my project? the code is:
protected void btnPreview_Click(object sender, EventArgs e)
{
lbHeader.Text = "Template Designer";
divQueryBuilder.Visible = false;
divTemplateDesigner.Visible = false;
divFloating.Visible = true;
if (txtQuery.Text.Contains("WHERE") || txtQuery.Text.Contains("where")||txtQuery.Text.Contains("Where"))
{
string[] splitter=new string[10];
splitter[0]="Where";
splitter[1]="WHERE";
splitter[2]="where";
splitter[3]="AND";
splitter[4] = "and";
splitter[5] = "And";
string[] condition=txtQuery.Text.Split(splitter, StringSplitOptions.None);
int numberOfParameters = condition.Length - 1;
string[] Condition1 =null;
Label[] newLabel = new Label[10];
TextBox[] txtBox = new TextBox[10];
for (int i = 0; i < numberOfParameters; i++)
{
string lbValue="lbValue";
string lbID=lbValue+i;
string txtValue = "txtValue";
string txtID = txtValue + i;
HtmlGenericControl genericControl = new HtmlGenericControl("br/");
Condition1 = condition[i + 1].Split('[', ']');
newLabel[i] = new Label();
txtBox[i] = new TextBox();
newLabel[i].ID=lbID;
newLabel[i].Text = Condition1[1];
txtBox[i].ID = txtID;
td2.Controls.Add(newLabel[i]);
td2.Controls.Add(genericControl);
td2.Controls.Add(txtBox[i]);
td2.Controls.Add(genericControl);
txtBox[i].EnableViewState = true;
}
}
}
private bool ControlExistence(string lbID)
{
try
{
td2.FindControl(lbID);
return true;
}
catch(Exception ex)
{
return false;
}
}
protected void btnOk_Click(object sender, EventArgs e)
{
// GetTextBoxValues();
string[] splitter1 = new string[10];
splitter1[0] = "Where";
splitter1[1] = "WHERE";
splitter1[2] = "where";
splitter1[3] = "AND";
splitter1[4] = "and";
splitter1[5] = "And";
string[] condition = txtQuery.Text.Split(splitter1, StringSplitOptions.None);
int numberOfParameters = condition.Length - 1;
string[] splitter = new string[4];
splitter[0] = "[";
splitter[1] = "]";
splitter[2] = "'";
string[] queryBoxValue = txtQuery.Text.Split(splitter,StringSplitOptions.RemoveEmptyEntries);
StringBuilder query = new StringBuilder();
TextBox txtBox = new TextBox();
for (int i = 0; i < queryBoxValue.Length; i++)
{
if (!queryBoxValue[i].Contains("?"))
{
query.Append(queryBoxValue[i]);
query.Append(" ");
}
else
{
for (int counter1 = 0; counter1 < numberOfParameters; counter1++)
{
string txtValue = "txtValue";
string txtID = txtValue + counter1;
if (ControlExistence(txtID))
{
TextBox box = (TextBox)td2.FindControl(txtID);
string b = box.Text;
//txtBox.ID = txtID;
}
txtBox.Text = "'" + txtBox.Text + "'";
queryBoxValue[i] = queryBoxValue[i].Replace(queryBoxValue[i], txtBox.Text);
query.Append(queryBoxValue[i]);
}
}
}
string fireQuery = query.ToString();
adp = new SqlDataAdapter(fireQuery, conn);
tab = new DataTable();
adp.Fill(tab);
if (tab.Rows.Count > 0)
{
string[] tempString = txtTemplate.Text.Split(' ');
for (int j = 0; j < tempString.Length; j++)
{
if (tempString[j].StartsWith("["))
{
txtPreview.Text = txtTemplate.Text.Replace(tempString[j], tab.Rows[0][0].ToString());
}
}
}
divFloating.Visible = false;
divQueryBuilder.Visible = false;
divTemplateDesigner.Visible = true;
}
Please help. This has become a blocker for me.
Have a list of the added controls and use it when needed.
for (int i = 0; i < numberOfParameters; i++)
{
// ...
td2.Controls.Add(newLabel[i]);
td2.Controls.Add(genericControl);
td2.Controls.Add(txtBox[i]);
td2.Controls.Add(genericControl);
addedTextBoxes.Add(txtBox[i]);
// ...
}
And then from another part of your code:
var values = addedTextBoxes.Select(tb => tb.Text).ToList();
foreach (var txtBox in addedTextBoxes)
{
// ...
}
etc...

Categories