ASP Is a foreach loop based on Button control on a Master page possible? - asp.net

I'm trying to dynamically turn off all buttons on a webpage for a practicular group of users. So what I want to do is just set visble and enable = false.
So i'm kind of looking for something like this below.
foreach(Button idvButton on Master)
{
idvButton.Visible = false;
idvButton.Enable = false;
}
Any help is appreciated! Thanks!

How about this from your child page's code behind?
foreach(var btn in Master.Page.Form.Controls.OfType<Button>())
{
btn.Visible = false;
btn.Enabled = false;
}

This disables all buttons found throughout entire MasterPage.
public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
disableButtons(ctrl);
}
}
void disableButtons(Control ctrl)
{
foreach (Control ctrl2 in ctrl.Controls)
{
if (ctrl2.GetType() == typeof(Button))
{
((Button)ctrl2).Enabled = false;
((Button)ctrl2).Visible = false;
}
}
}
}

Here is the answer: Had to combine both previous posts.
foreach (var btn in this.Page.Form.Controls.OfType<RadButton>())
{
btn.Visible = false;
btn.Enabled = false;
}

Related

how to data bind to dropdownlist when checkbox is checked in asp.net

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

Find all textbox control in a page

i am trying to use http Module to disable textbox of each page. Here is my sample coding
public void context_OnPreRequestHandlerExecute(object sender, EventArgs args)
{
try
{
HttpApplication app = sender as HttpApplication;
if (app != null)
{
Page page = app.Context.Handler as Page;
if (page != null)
{
page.PreRender += OnPreRender;
page.PreLoad += onPreLoad;
}
}
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
public void OnPreRender(object sender, EventArgs args)
{
Page page = sender as Page;
if (page.IsCrossPagePostBack)
{
DisableAllTextBoxes(page);
}
}
private static void DisableAllTextBoxes(Control parent)
{
foreach (Control c in parent.Controls)
{
var tb = c as Button;
if (tb != null)
{
tb.Enabled = false;
}
DisableAllTextBoxes(c);
}
}
This coding can work very well but when i use server.transer to another page. Button are not able to disable already.
For example webform1 transfer to webform2. Webform 1's button is able to disable but webform2 is not able to disable. Can anyone solve my problem?
Server.Transfer DOES NOT go through all http module pipline (thats why context_OnPreRequestHandlerExecute isn't executed for you )
you should try Server.TransferRequest or response.redirect or HttpContext.Current.RewritePath
Use LINQ to get all your textbox controls.
Don't use Server.Transfer()
Create an extension method on ControlCollection that returns an IEnumerable. That handles the recursion. Then you could use it on your page like this:
var textboxes = this.Controls.FindAll().OfType<TextBox>();
foreach (var t in textboxes)
{
t.Enabled = false;
}
...
public static class Extensions
{
public static IEnumerable<Control> FindAll(this ControlCollection collection)
{
foreach (Control item in collection)
{
yield return item;
if (item.HasControls())
{
foreach (var subItem in item.Controls.FindAll())
{
yield return subItem;
}
}
}
}
}
Taken from this answer.

Programmatically created CheckBoxList not firing when "unchecked"

I'm using ASP.NET and C#. I'm programmtically creating a checkboxlist. When I check an item, the SelectedIndexChanged event is firing. But, when I uncheck the item, the event is not fired. I'm binding the items on every postback and autopostback is set to true. Where am I going wrong? Here's the code -
page_load
{
var cblUser = new CheckBoxList();
cblUser.AutoPostBack = true;
cblUser.SelectedIndexChanged += cblUser_SelectedIndexChanged;
var list = DAL.GetUsers();
foreach (var user in list)
{
cblUser.Items.Add(new ListItem(user.Name, user.Id));
}
}
Thank you.
Update #1: Actual code -
public partial class CategoriesAccordion : UserControl
{
public List<Community> AllCommunities
{
get
{
if (Session["AllCommunities"] == null)
{
var db = new CommunityGuideDB();
Session["AllCommunities"] = db.Communities.OrderBy(x => x.Name).ToList();
}
return (List<Community>) Session["AllCommunities"];
}
}
public List<Category> Categories
{
get
{
if (Session["Categories"] == null)
{
var db = new CommunityGuideDB();
Session["Categories"] = db.Categories.OrderBy(x => x.Name).ToList();
}
return (List<Category>) Session["Categories"];
}
}
public event EventHandler Categories_Selected = delegate { };
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) Session.Remove("Categories");
LoadCategories();
}
private void LoadCategories()
{
foreach (var parent in Categories.Where(item => item.ParentId == null && item.ShowAsPivot == true).OrderBy(x => x.DisplayOrder))
{
var pane = new AccordionPane {ID = parent.Name};
pane.HeaderContainer.Controls.Add(new LiteralControl(parent.Name));
var cblValues = new CheckBoxList();
cblValues.AutoPostBack = true;
cblValues.SelectedIndexChanged += cblValues_SelectedIndexChanged;
foreach (var child in Categories.Where(child => child.ParentId == parent.Id))
{
var communityCount = child.CommunityCategory.Where(x => x.Categories_Id == child.Id).Count();
cblValues.Items.Add(new ListItem(string.Format("{0} ({1})", child.Name, communityCount), child.Id.ToString()));
}
pane.ContentContainer.Controls.Add(cblValues);
acdFilters.Panes.Add(pane);
}
}
protected void cblValues_SelectedIndexChanged(object sender, EventArgs e)
{
var cblValues = ((CheckBoxList) sender);
var selectedCategories = (from ListItem item in cblValues.Items where item.Selected select Categories.Find(c => c.Id == new Guid(item.Value))).ToList();
Categories_Selected(this, new CommandEventArgs("SelectedCategories", selectedCategories));
}
}
I don't get how do you add the control to a container?
I've just checked and I've got the event fired both on checking & unchecking.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckBoxList cbList = new CheckBoxList();
cbList.AutoPostBack = true;
for (int i = 0; i < 10; i++)
cbList.Items.Add(i.ToString());
cbList.SelectedIndexChanged += new EventHandler(cbList_SelectedIndexChanged);
form1.Controls.Add(cbList);
}
void cbList_SelectedIndexChanged(object sender, EventArgs e)
{
//fires both on check & uncheck of an item
}
}
The SelectedIndexChanged event you are bounding is fired upon selecting different item on your list, not when you check an item. CheckBoxList does not have an event for changing the status of its items.
Try a to use list control like Repeater ...

Hiding a LinkButton in DataList

Hi someone can tell me how to hide a LinkButton inside a DataList?
I've tried to do this but I do not work:
protected void Page_PreRender(object sender, EventArgs e)
{
foreach (var item in listanews)
{
DataList container = dlgestionenews;
if (string.IsNullOrEmpty(item.IdNews))
{
DataListItem itemdatalist = null;
foreach (DataListItem itemdl in container.Items)
{
foreach (Control control in itemdatalist.Controls)
{
if (control.GetType().FullName == "LinkButton")
{
((LinkButton)control).Visible = false;
}
}
}
}
}
}
Thanks!
Try this:
foreach (DataListItem dli in yourDataListControl.Items)
{
LinkButton lbLinkButton = (LinkButton)dli.FindControl("yourLinkButtonID");
if (lbLinkButton != null)
{
lbLinkButton.Visible = false;
}
}
You should move this code to the
protected virtual void OnItemDataBound(
DataListItemEventArgs e
)
event. In this event, you should use the e.Item.FindControl('LinkButtonID') method for the finding your control
More info is here

How can I change the field type on a GridView at runtime with AutoGenerate="True"?

I've created a control that extends the BoundField control to do some special processing on the data that's passed into it.
I now have a grid that has AutoGenerateColumns="true", by which I'd like to intercept the HeaderText, see if it's a particular value and then swap in the "SpecialBoundField" instead. I've tried using the OnDataBinding event to loop through the columns, but at this point there are no columns in the grid. I think that RowDataBound and DataBound are too late in the game so not sure what to do.
My next thought was to override the grid control itself to add in a "AutoGeneratingColumn" event in
protected virtual AutoGeneratedField CreateAutoGeneratedColumn(AutoGeneratedFieldProperties fieldProperties)
Can anyone help or point me in a better direction? Thanks!
If you have both fields coming back in the dataset, I would suggest setting the column visibilities instead of trying to dynamically add or change the datafields. Invisible columns don't render any HTML, so it would just be a matter of looking at the header row when it gets bound, checking the field you're interested in, and setting the column visibility.
void myGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
if (e.Row.Cells[1].Text = "BadText")
{
myGridView.Columns[1].Visible = false;
myGridView.Columns[5].Visible = true;
}
}
}
What I ended up with:
public class SpecialGridView : GridView
{
protected override void OnRowDataBound(GridViewRowEventArgs e)
{
ModifyData(e);
base.OnRowDataBound(e);
}
IList<string> _columnNames = new List<string>();
protected void ModifyData(GridViewRowEventArgs e)
{
LoadColumnNames(e);
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
string currentColumnName = _columnNames[i];
if (IsSpecialColumn(currentColumnName))
{
string text = e.Row.Cells[0].Text;
bool isSpecialData = text.ToUpper() == "Y";
if (isSpecialData)
{
e.Row.Cells[i].CssClass += " specialData";
}
}
}
}
}
private void LoadColumnNames(GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell cell in e.Row.Cells)
{
_columnNames.Add(cell.Text);
}
}
}
private bool IsSpecialColumn(string currentColumnName)
{
foreach (string columnName in SpecialColumnNames)
{
if (currentColumnName.ToUpper() == columnName.ToUpper())
{
return true;
}
}
return false;
}
private IList<string> _specialColumnNames = new List<string>();
public IList<string> SpecialColumnNames
{
get { return _specialColumnNames; }
set { _specialColumnNames = value; }
}
}

Resources