I generate my check boxes dynamically:
for (int i = 0; i < dtCommon.Count; i++)
{
CheckBox newBox = new CheckBox();
newBox.Text = dtCommon[i].userName;
newBox.CssClass = "cbox";
if (dtCommon[i].isAlreadyRequired > 0 )
{
newBox.CssClass = "cbox highlighted";
newBox.Checked = true;
}
ApprovalSelectPanel.Controls.Add(newBox);
}
And when the save button is pressed I call this function:
protected void SaveUsers(object sender, EventArgs e)
{
}
How do I know which check boxes the user has checked?!
You could loop through the ApprovalSelectPanel.Controls and cast them back to the corresponding CheckBox type and verify the Checked property.
I think it is better to use CheckBoxList Within the ApprovalSelectPanel instead of add it in the runtime and in the runtime do the following
CheckBoxList1.DataSource = dtCommon;
CheckBoxList1.DataMember = "userName";
CheckBoxList1.DataBind();
To know which one is selected do the following
foreach(ListItem item in CheckBoxList1.Items)
if (item.Selected)
{
//Do any action
}
Related
I have a project that using dropdownlist for choices.When check checkbox1 dropdown automatically bind data from database using table1 and when I check checkbox2 dropdown automatically binding data from database using table2.I do not want to use get data by using any button .How can I do that .Please help me.
here is code by using button:
public void LokasyonDoldur()
{
birimBUS = new BirimBUSV1();
List<BirimVO> birimVO = new List<BirimVO>();
DrpChcs.Items.Clear();
List<ListItem> items = new List<ListItem>();
birimVO = birimBUS.LokasyonlariGetir();
foreach (var item in birimVO)
{
items.Add(new ListItem(item.BirimAdi, item.ID.ToString()));
}
DrpChcs.Items.AddRange(items.ToArray());
}
public void BirimleriDoldur()
{
PoliklinikBUS poliklinikBUS = new PoliklinikBUS();
List<PoliklinikVO> poliklinikVO = new List<PoliklinikVO>();
DrpChcs.Items.Clear();
List<ListItem> items = new List<ListItem>();
poliklinikVO = poliklinikBUS.Poliklinikler();
foreach (var item in poliklinikVO)
{
items.Add(new ListItem(item.PoliklinikAdi, item.ID.ToString()));
}
DrpChcs.Items.AddRange(items.ToArray());
}
protected void BtnLokasyon_Click(object sender, EventArgs e)
{
if (ChckLctn.Checked == true && ChckBrm.Checked==false)
{
LokasyonDoldur();
}
else if (ChckLctn.Checked == false && ChckBrm.Checked == true)
{
BirimleriDoldur();
}
else
{
}
Button1.Visible = true;
BtnLokasyon.Visible = false;
}
protected void DrpChcs_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
KirilimId = Int32.Parse(DrpChcs.SelectedValue);
BPolikilinikID= KirilimId;
}
but I do not want to use this one.
ohh its another language. its hard to read. but what you basicly have to do is check which checkbox is checked in the page load and then load the dropdown based on what is loaded.
something like this. (I have typed it from my head so its not like copy-paste but you get the idea)
page_load
{
if(checkbox1.checked)
{
dropdown.dataitems = items1;
dropdown.databind();
return;
}
if(checkbox2.checked)
{
dropdown.dataitems = items2;
dropdown.databind();
return;
}
}
YOu can call the Button1_click event from the Dropdown list selected index changed event like this
Button1_Click(Button1,new EventArgs());
and in this you can hide that button from the page and in code behind you are calling the same function
OR
You can refactor the code in a seperate function from the button click event and call that function in the selected index changed event.
Please let me knwo if I misunderstood your question
Thanks
I am creating a tree programmatically inside a row in a table.
Works fine, but can not get the assigned event is called:
TreeView arbolCapas = new TreeView();
arbolCapas.ID = "capas";
foreach (String capa in servicio.Capas)
{
TreeNode childNodes = new TreeNode();
childNodes.Text = capa;
childNodes.ShowCheckBox = true;
childNodes.SelectAction = TreeNodeSelectAction.None;
arbolCapas.Nodes.Add(childNodes);
}
arbolCapas.SelectedNodeChanged +=new EventHandler(arbolCapas_TreeNodeCheckChanged);
tbC.Controls.Add(arbolCapas);
tbR.Cells.Add(tbC);
protected void arbolCapas_TreeNodeCheckChanged(Object sender, EventArgs e)
{
TreeView elemento = (TreeView)(((CheckBox)sender).Parent);
foreach (TreeNode node in elemento.CheckedNodes)
{ //if (node.Checked)
}
}
How I can call an event when the checkbox of a child node is checked?
Thanks a lot.
Kindly change
childNodes.SelectAction = TreeNodeSelectAction.None
to
childNodes.SelectAction = TreeNodeSelectAction.Select;
I found the solution by adding the event as follows:
arbolCapas.Attributes.Add("onclick", "OnCheckBoxCheckChanged(event)");
And then, in javascript:
function OnCheckBoxCheckChanged(evt) {
alert("check change");
}
Here the solution:
http://geekswithblogs.net/ranganh/archive/2009/01/21/updated-asp.net-treeview-checkboxes-ndash-check-all-ndash-javascript.aspx
In my project I've got a variable numtorust which represents the number of the toursits.
(for testing purposes numtourist = 2)
for (i=0,numtoursut; i++)
I create dynamically 5 checkboxes with assigned checkedChanged event for each of tourist. Also to keep track which checkbox to which tourist applies I add attribute 'collection'
mycheckbox.InputAttributes.Add("collection", i.ToString());
In checkedchanged event handler - when a user selects a checkbox I checked if its collection attribute is = 0 or 1 (first or second user). then I add checkbox value to myche1 which is of type List<string) if collection attribute = 1.
But I when I decided to make one array of type List<string> with name Toursit
when I try to add an element to it I got an exception - Object reference not set to an instance of object in this row of my code
Toursist[Int32.Parse(chk.InputAttributes["collection"])].Add(chk.InputAttributes["value"].ToString());
Here is my full code
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
/*that doesn't work
if (chk.Checked)
{
Toursist[Int32.Parse(chk.InputAttributes["collection"])].Add(chk.InputAttributes["value"].ToString());
((List<String>[])Session["chk"])[Int32.Parse(chk.InputAttributes["collection"])] = Toursist[Int32.Parse(chk.InputAttributes["collection"])];
}*/
//this works with myche1 of type list<string>
if ((chk.Checked)&&(chk.InputAttributes["collection"].Equals("1")))
{
myche1.Add(chk.InputAttributes["value"].ToString());
lblProba.Text += chk.InputAttributes["value"].ToString();
Session["chk1"] = myche1;
}
}
edit 1:
teh new code of
protected void checkChanged(object sender, EventArgs e)
{
List<string>[] Toursist = new List<string>[2];
//Session["chk"] = new List<string>[2];
for (int i = 0; i < Toursist.Length; i++)
{
Toursist[i] = new List<string>();
// ((List<String>[])Session["chk"])[i] = Toursist[i];
}
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
if (((List<String>[])Session["chk"])[Int32.Parse(chk.InputAttributes["collection"])] == null)
{
((List<String>[])Session["chk"])[Int32.Parse(chk.InputAttributes["collection"])] = Toursist[Int32.Parse(chk.InputAttributes["collection"])];
}
Toursist[Int32.Parse(chk.InputAttributes["collection"])].Add(chk.InputAttributes["value"].ToString());
lblProba.Text += chk.InputAttributes["collection"].ToString();
((List<String>[])Session["chk"])[Int32.Parse(chk.InputAttributes["collection"])] = Toursist[Int32.Parse(chk.InputAttributes["collection"])];
}
again the same mistake this time when I test if Sessio["chk"] == 0.
but If I uncomment (so I no more have this mistake)
// ((List<String>[])Session["chk"])[i] = Toursist[i];
on each postback event my session will be empty and I don't want!!
You haven't created any lists. When you create an array of lists, it won't automatically create all the lists in the array, you have to do that manually:
List<string>[] Toursist = new List<string>[numtoursut];
for (int i = 0; i < Toursist.Length; i++) {
Toursist[i] = new List<string>();
}
i have created ListBox's Dynamically in a panel and i want to read the selected item from the Listbox created dynamically . below is the code that i used to create the Dynamic Listbox. can anyone please help me how to get the dynamically created listbox and then read the item selected. 'protected void GotoReport_Click(object sender, ImageClickEventArgs e)
{
foreach (TreeNode tndim in tvCubedef.CheckedNodes)
{
lbFilter.Items.Add(tndim.Text);
}
foreach (ListItem item in lbFilter.Items)
{
item.Selected = true;
}
panFilter.Controls.Clear();
connstr2 = System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
conn2.ConnectionString = connstr2;
conn2.Open();
CubeCollection CubeList = conn2.Cubes;
string cb = ddlCubeList.SelectedItem.Text;
foreach (ListItem li in lbFilter.Items)
{
ListBox listb = new ListBox();
ListItem Memlist = new ListItem();
listb.SelectionMode = System.Web.UI.WebControls.ListSelectionMode.Multiple;
listb.Height = 150;
listb.Width = 250;
string Repl1 = li.Value.Replace("[", "");
string Repl2 = Repl1.Replace("]", "");
string[] DimMember = Repl2.Split('.');
foreach (Member dimem in CubeList[cb].Dimensions[DimMember[0]].Hierarchies[DimMember[1]].Levels[DimMember[2]].GetMembers())
{
Memlist.Text = dimem.Name;
listb.Items.Add(Memlist);
panFilter.Controls.Add(listb);
}
}
} '
You need to add the event-handler dynamically:
listb.SelectedIndexChanged += new EventHandler(listb_SelectedIndexChanged);
Of course you also need to provide this method:
protected void listb_SelectedIndexChanged(Object sender, EventArgs e)
{
ListBox listb = (ListBox) sender;
}
Are you recreating this ListBox on every postback (as you should) in page_load at the latest and with same ID as before?
This must be something that a lot of people have done. Basically, it's a custom GridView (i.e. inherited control) with the ability to update all rows at once. I've tried putting the "update all" button in various places (footer, pager, outside the grid), but it looks neatest (to me) when the button is in an extra row as the last row of the GridView.
NB: The pager row is not a suitable place for this button because this custom control could be used in a situation where paging is false. Similarly, the normal footer may be required for some other purpose (e.g. totals).
Here's my code for putting the button in the correct place (with apologies for the terse variables etc.):
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
//Add an extra row to the table...
if (_updateAllEnabled)
{
GridViewRow r = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
Button btn = new Button();
TableCell c = new TableCell();
btn.ID = "UpdateAllButton"; // tried with and without this line
btn.Text = "Update All";
btn.Click += new EventHandler(UpdateAll);
r.Cells.Add(c);
c.Controls.Add(btn);
Table t = this.Controls[0] as Table;
c.ColumnSpan = this.Columns.Count;
t.Rows.Add(r);
}
}
This gives the appearance that I want, but the click event (UpdateAll) does not fire.
I assume that the stuff is being added too late in the life cycle (PreRender), but where else can I do this to ensure that the row is at the end of the GridView? I also thought that there might be trouble identifying the button, so I tried setting the ID. In any case, the ID in the generated HTML looks OK (consistent with "working" buttons in the pager row.
Is there a way for me to achieve this or am I attempting the impossible?
The best place to create your footer-controls is RowCreated since that's early enough in the lifecycle and also ensures that their recreated on every postback:
Footer approach:
protected void Grid_RowCreated(Object sender, GridViewRowEventArgs e) {
if(e.Row.RowType == DataControlRowType.Footer) {
Button btn = new Button();
TableCell c = new TableCell();
btn.ID = "UpdateAllButton";
btn.Text = "Update All";
btn.Click += new EventHandler(UpdateAll);
var firstCell=e.Row.Cells[0];
firstCell.ColumnSpan =e.Row.Cells.Count;
firstCell.Controls.Add(btn);
while(e.Row.Cells.Count > 1)e.Row.Cells.RemoveAt(e.Row.Cells.Count-1);
}
}
Of course you have to set ShowFooter to true:
<asp:GridView ID="GridView1"
ShowFooter="true"
OnRowCreated="Grid_RowCreated"
runat="server"
</asp:GridView>
Pager approach:
In my opinion this is the purpose of the FooterRow. But if you really want to ensure that your Button is in the very last row of a GridView(even below Pager as commented), i would try my next approach.
Here I'm using the pager for your costom control(s) by adding another TableRow to the PagerTable which inherits from Table.
protected void Grid_RowCreated(Object sender, GridViewRowEventArgs e) {
switch(e.Row.RowType){
case DataControlRowType.Pager:
Button btnUpdate = new Button();
btnUpdate.ID = "UpdateButton";
btnUpdate.Text = "Update";
btnUpdate.Click += new EventHandler(UpdateAll);
var tblPager = (Table)e.Row.Cells[ 0 ].Controls[ 0 ];
var row = new TableRow();
var cell = new TableCell();
cell.ColumnSpan = tblPager.Rows[ 0 ].Cells.Count;
cell.Controls.Add(btnUpdate);
row.Cells.Add(cell);
tblPager.Rows.Add(row);
break;
}
}
To ensure that the pager is visible even if only one page is shown(note that the real pager is invisible if PageSize==1):
protected void Grid_PreRender(object sender, EventArgs e){
GridView gv = (GridView)sender;
GridViewRow gvr = (GridViewRow)gv.BottomPagerRow;
if(gvr != null) {
gvr.Visible = true;
var tblPager = (Table)gvr.Cells[ 0 ].Controls[ 0 ];
//hide real pager if unnecessary
tblPager.Rows[ 0 ].Visible = GridView1.PageCount > 1;
}
}
Of course now you have to set AllowPaging=true:
<asp:GridView ID="GridView1"
AllowPaging="true"
PagerSettings-Mode="NumericFirstLast"
OnRowCreated="Grid_RowCreated"
OnPreRender="Grid_PreRender"
OnPageIndexChanging="Grid_PageChanging"
runat="server">
</asp:GridView>
Final approach(working for a custom GridView and all PagerPositions):
public PagerPosition OriginalPagerPosition{
get { return (PagerPosition)ViewState[ "OriginalPagerPosition" ]; }
set { ViewState[ "OriginalPagerPosition" ] = value; }
}
protected void Page_Load(object sender, EventArgs e){
if(!IsPostBack) OriginalPagerPosition = GridView1.PagerSettings.Position;
GridView1.PagerSettings.Position = PagerPosition.TopAndBottom;
GridView1.AllowPaging = true;
// databinding stuff ...
}
Keep the RowCreated the same as above in Pager approach.
Visibility of top/bottom pagers will be controlled in PreRender according to the OriginalPagerPosition property. Both pagers are created even with PagerPosition=TOP, the bottom pager is required for your additional control(s):
protected void Grid_PreRender(object sender, EventArgs e)
{
GridView gv = (GridView)sender;
GridViewRow tpr = (GridViewRow)gv.TopPagerRow;
GridViewRow bpr = (GridViewRow)gv.BottomPagerRow;
tpr.Visible = gv.PageCount > 1 && (OriginalPagerPosition == PagerPosition.Top || OriginalPagerPosition == PagerPosition.TopAndBottom);
bpr.Visible = true;
var tblBottomPager = (Table)bpr.Cells[ 0 ].Controls[ 0 ];
tblBottomPager.Rows[ 0 ].Visible = gv.PageCount > 1 && (OriginalPagerPosition == PagerPosition.Bottom || OriginalPagerPosition == PagerPosition.TopAndBottom);
var tblTopPager = (Table)tpr.Cells[ 0 ].Controls[ 0 ];
tblTopPager.Rows[1].Visible = false;
}
Note: if you are extending the GridView control, you have to replace all occurences of GridView1(my test-grid) with this.
It would be easy to add an extra row into the grid. But the difficulty in your requirement is that the GridView's RowCollection should not contain this row since that would be error-prone. It should also be the very last row even if paging is enabled. This is (afaik) not possible.
Hence i've chosen to extend the pager with this functionality.
I'll add this as separate answer since my other is already too detailed and describes two different ways(footer,pager) to add controls to a GridView without extending it.
This approach extends a GridView as in your own requirement and is similar to my other pager-approach. But it's cleaner and only adds the additional row to the BottomPager. It woks also for every setting(AllowPaging=false,Pager-Position: Top,Bottom,BottomTop):
[DefaultProperty("EnableUpdateAll")]
[ToolboxData("<{0}:UpdateGridView runat=server></{0}:UpdateGridView>")]
public class UpdateGridView : GridView
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("true")]
[Localizable(true)]
public bool EnableUpdateAll
{
get
{
Object val = ViewState["EnableUpdateAll"];
return ((val == null) ? true : (bool)val);
}
set
{
ViewState["EnableUpdateAll"] = value;
}
}
private bool OriginalAllowPaging
{
get
{
Object val = ViewState["OriginalAllowPaging"];
return (bool)val;
}
set
{
ViewState["OriginalAllowPaging"] = value;
}
}
private PagerPosition OriginalPagerPosition
{
get
{
Object val = ViewState["OriginalPagerPosition"];
return (PagerPosition)val;
}
set
{
ViewState["OriginalPagerPosition"] = value;
}
}
protected override void OnInit(System.EventArgs e)
{
if (ViewState["OriginalPagerPosition"] == null)
OriginalPagerPosition = base.PagerSettings.Position;
if(OriginalPagerPosition != PagerPosition.Bottom)
PagerSettings.Position=PagerPosition.TopAndBottom;
if (ViewState["OriginalAllowPaging"] == null)
OriginalAllowPaging = base.AllowPaging;
base.AllowPaging = true;
}
protected override void OnRowCreated(GridViewRowEventArgs e)
{
switch (e.Row.RowType)
{
case DataControlRowType.Pager:
//check if we are in BottomPager
if (this.Rows.Count != 0 && this.EnableUpdateAll)
{
Button btnUpdate = new Button();
btnUpdate.ID = "BtnUpdate";
btnUpdate.Text = "Update";
btnUpdate.Click += new EventHandler(UpdateAll);
var tblPager = (Table)e.Row.Cells[0].Controls[0];
var row = new TableRow();
var cell = new TableCell();
cell.ColumnSpan = tblPager.Rows[0].Cells.Count;
cell.Controls.Add(btnUpdate);
row.Cells.Add(cell);
tblPager.Rows.Add(row);
}
break;
}
}
protected override void OnPreRender(EventArgs e)
{
bool bottomPagerVisible =
OriginalAllowPaging &&
PageCount > 1 &&
(OriginalPagerPosition == PagerPosition.Bottom || OriginalPagerPosition == PagerPosition.TopAndBottom);
BottomPagerRow.Visible = bottomPagerVisible || EnableUpdateAll;
var tblBottomPager = (Table)BottomPagerRow.Cells[0].Controls[0];
tblBottomPager.Rows[0].Visible = bottomPagerVisible;
}
private void UpdateAll(Object sender, EventArgs e)
{
// do something...
}
}