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
}
}
}
}
}
}
}
}
Related
I have created a small kitchen display program that display food orders. So I created dynamically a panel that contains a table layout panel that contains a checked list box and a check all button . My problem is... I have a check all button in each table layout panel created dynamically and every time I click it, it checks all items in the last created CheckedListBox not the clicked one.
This is my code:
p = new Panel();
p.Size = new System.Drawing.Size(360, 500);
p.BorderStyle = BorderStyle.FixedSingle;
p.Name = "panel";
tpanel = new TableLayoutPanel();
tpanel.Name = "tablepanel";
clb = new CheckedListBox();
tpanel.Controls.Add(b1 = new Button() { Text = "CheckAll" }, 1, 4);
b1.Name = "b1";
b1.Click += new EventHandler(CheckAll_Click);
b1.AutoSize = true;
private void CheckAll_Click(object sender, EventArgs e)
{
var buttonClicked = (Button)sender;
var c = GetAll(this, typeof(CheckedListBox));
for (int i = 0; i < c.Count(); i++)
{
\\any help
}
}
public IEnumerable<Control> GetAll(Control control, Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll(ctrl, type)).Concat(controls).Where(c =>
c.GetType() == type);
}
First I will describe the struct
Order = TableLayoutPanel
TableLayoutPanel has 1 CheckAll Button and CheckListBox
And you want when you click to CheckAll Button it will checks exactly all items in current TableLayoutPanel.
So try this code
class XForm : Form {
// create Dictionary to store Button and CheckListBox
IDictionary<Button, CheckListBox> map = new Dictionary<Button, CheckListBox> ();
// when you create new order (new TableLayoutPanel)
// just add map Button and CheckListBox to map
private void CreateOrder () {
var panel = new Panel ();
panel.Size = new System.Drawing.Size (360, 500);
panel.BorderStyle = BorderStyle.FixedSingle;
panel.Name = "panel";
var table = new TableLayoutPanel ();
var checklistBox = new CheckedListBox ();
var button = new Button () { Text = "CheckAll" };
table.Controls.Add (button, 1, 4);
button.Name = "b1";
button.Click += new EventHandler (CheckAll_Click);
button.AutoSize = true;
map[button] = checklistBox;
}
// and on event handle
private void CheckAll_Click (object sender, EventArgs e) {
var buttonClicked = (Button) sender;
var c = map[buttonClicked];
if (c == null) return;
for (int i = 0; i < c.Items.Count; i++)
{
c.SetItemChecked(i, true);
}
}
}
And dont for get remove it from map when remove the order.
Hope it helps
I am creating a five checkboxes dynamiclly with a for loop inside a GroupBox.
now, they were created dynamiclly, so I don't know how can I make a ChangeCheck method attached to them?
All those checkoxes are related so what I am trying to do is something like that:
create 5 checkboxes dynamiclly
add each checkbox to a list
when a specific checkbox in the list is on trigger a method.
this is how I create the checkboxes:
for (int i = 0; i < 5; i++)
{
CheckBox chk = new CheckBox();
chk.size = new Size(10, 10);
chk.Top = 10
chk.Left = 20
chk.Text = i.ToString();
group_box_name.controls.Add(chk);
}
Now, how can I detect which checkbox was on/off?
You could do the following:
int top = 0;
for (int i = 0; i < 5; i++)
{
CheckBox chk = new CheckBox();
chk.size = new Size(10, 10);
chk.Top += (5 + 10); //Spacing = 5, CheckboxHeight = 10
chk.Left = 20;
chk.Text = i.ToString();
chk.CheckedChanged += CheckBox_CheckedChanged;
chk.Tag = i;/*You can put anything here.
Otherwise you could also use the Name property..
It just helps to determine which checkbox was currently checked */
group_box_name.controls.Add(chk);
}
private void checkBox_CheckedChanged(object sender, System.EventArgs e)
{
CheckBox cbx = (CheckBox)sender;
if(cbx != null)
{
int tag = int.Parse(cbx.Tag.ToString());
switch(tag)
{
case 0:
//Do whatever:
break;
//Handle other cases here:
}
}
}
Add checked change event to your dynamically created checkbox. You can add name also
for (int i = 0; i < 5; i++)
{
CheckBox chk = new CheckBox();
chk.Name = "chk" + i.ToString();
chk.size = new Size(10, 10);
chk.Top = 10
chk.Left = 20
chk.Text = i.ToString();
chk.CheckedChanged += checkBox_CheckedChanged;
group_box_name.controls.Add(chk);
}
private void checkBox_CheckedChanged(object sender, System.EventArgs e)
{
CheckBox chk=sender as CheckBox;
if(chk!=null)
{
if(chk.Checked)
{
string chkName=chk.Name;
string chkText=chk.Text;
//your code
}
}
}
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);
}
}
}
I am developing mobile application in C#. I want to add the checkbox control dynamically at the beginning of every row in the datagrid control & based on that particular checkbox selection I want to fire the event. I want to add the checkbox column & based on the selection of any particular checkbox, I want to fire the event on that checkbox selected row. I am using the following code.
private void ShowRegistrationKeyDetails_Load(object sender, EventArgs e)
{
GridHeight = 40;
SQLiteDataReader SQLiteDrKeyObj = null;
DataTable dt = new DataTable();
DataManager DataMgrObj = new DataManager();
//int KeyID = Cust_ID;
//string Client_Key1 = Client_Key;
int KeyID = Selected_Customer_ID;
//string Client_Key = Selected_Client_Key;
SQLiteDrKeyObj = DataMgrObj.getRegistrationKey(KeyID);
dt.Load(SQLiteDrKeyObj);
//dt.Columns.Add(new DataColumn("Select", typeof(Boolean)));
RegKeyInfodataGrid.DataSource = dt;
SizeColumns(RegKeyInfodataGrid);
RegKeyInfodataGrid.Height = GridHeight;
}
protected void SizeColumns(DataGrid grid)
{
//grid.Controls.Add(new CheckBox());
Graphics g = CreateGraphics();
DataTable dataTable = (DataTable)grid.DataSource;
//DataColumn dtcCheck = new DataColumn("IsMandatory");//create the data
////column object with the name
//dtcCheck.DataType = System.Type.GetType("System.Boolean");//Set its
////data Type
//dtcCheck.DefaultValue = false;//Set the default value
//dataTable.Columns.Add(dtcCheck);//Add the above column to the
//Data Table
//Set the Data Grid Source as the Data Table createed above
//grid.DataSource = dataTable1;
// set style property when first time the grid loads, next time onwards // it will maintain its property
DataGridTableStyle dataGridTableStyle = new DataGridTableStyle();
dataGridTableStyle.MappingName = dataTable.TableName;
int RowCount = dataTable.Rows.Count;
//foreach(
foreach (DataColumn dataColumn in dataTable.Columns)
{
int maxSize = 0;
SizeF size = g.MeasureString(
dataColumn.ColumnName,
grid.Font
);
if (size.Width > maxSize)
maxSize = (int)size.Width;
//grid.Controls.Add(new CheckBox());
foreach (DataRow row in dataTable.Rows)
{
size = g.MeasureString(
row[dataColumn.ColumnName].ToString(),
grid.Font
);
if (size.Width > maxSize)
maxSize = (int)size.Width;
// AutoResize DataGrid Control
string Act_Date = dataColumn.ColumnName;
if (Act_Date == "Activation_Date")
{
GridHeight = GridHeight + 17;
//CheckBox chk = new CheckBox();
//chk.Location = new Point(20, 30);
//this.Controls.Add(chk);
//dataTable.Rows.Add(new CheckBox());
}
}
DataGridColumnStyle dataGridColumnStyle = new DataGridTextBoxColumn();
dataGridColumnStyle.MappingName = dataColumn.ColumnName;
dataGridColumnStyle.HeaderText = dataColumn.ColumnName;
dataGridColumnStyle.Width = maxSize + 5;
dataGridTableStyle.GridColumnStyles.Add(dataGridColumnStyle);
}
grid.TableStyles.Add(dataGridTableStyle);
g.Dispose();
}
private void BackmenuItem_Click(object sender, EventArgs e)
{
QueryDetails QueryDetailsObj = new QueryDetails();
QueryDetailsObj.Show();
}
Can you please provide me any code or link through which I can resolve the above issue?
There is an example of adding a check box to a Datagrid:
http://www.codeproject.com/Articles/2652/Adding-a-CheckBox-column-to-your-DataGrid
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.