Hiding a LinkButton in DataList - asp.net

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

Related

How to paint cells in row (Telerik)?

I've next code that handle fowFormatting my cells:
private void gridViewRaces_RowFormatting(object sender, RowFormattingEventArgs e)
{
foreach (var cellColumn in e.RowElement.Data.Cells)
{
var cellInfo = cellColumn as GridViewCellInfo;
if (cellInfo != null)
{
cellInfo.Style.DrawFill = true;
if (cellInfo.ColumnInfo.Name == "columnContactProducerName")
{
cellInfo.Style.DrawFill = true;
cellInfo.Style.BackColor = Color.Yellow;
}
else if (cellInfo.ColumnInfo.Name == "columnTransport")
{
cellInfo.Style.BackColor = Color.Yellow;
}
else
{
cellInfo.Style.BackColor = ColorTranslator.FromHtml((e.RowElement.Data.DataBoundItem as RaceForListDto).Color);
}
}
}
//e.RowElement.BackColor = ColorTranslator.FromHtml((e.RowElement.Data.DataBoundItem as RaceForListDto).Color);
}
but my cells aren't painting. How to paint some cells in rows on dataBinding?
It looks like the proper event to do this is ItemDataBound event. See here:
http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/appearance-and-styling/conditional-formatting
protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
//Is it a GridDataItem
if (e.Item is GridDataItem)
{
//Get the instance of the right type
GridDataItem dataBoundItem = e.Item as GridDataItem;
//Check the formatting condition
if (int.Parse(dataBoundItem["Size"].Text) > 100)
{
dataBoundItem["Received"].ForeColor = Color.Red;
dataBoundItem["Received"].Font.Bold = true;
//Customize more...
}
}
}
Or event better is to use a custom CSS class so that you can later make changes without having to rebuild the project:
protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e){
if (e.Item is GridDataItem)
{
GridDataItem dataItem = e.Item as GridDataItem;
if (dataItem["Country"].Text == "Mexico")
dataItem.CssClass = "MyMexicoRowClass";
}
}

Hiding GridView Columns on RunTime

i am trying to hid some columns of gridView on run time by matching their HeaderText but its not working for me. here is the code i am trying
protected void gridview_rowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (DataControlField col in gvRecoed.Columns)
{
try
{
if (col.HeaderText == cat_check.SelectedItem.Text.Trim())
{
col.Visible = false;
}
}
catch (Exception exe)
{ }
}
}
cat_check is a CheckBoxList
Why do you want to hide the column in RowDataBound which is triggered for every row in the grid?
Instead you could use the DataBound event which is called once after the grid was databound.
protected void gridview_DataBound(object sender, EventArgs e)
{
if(cat_check.SelectedItem != null)
{
string columnName = SelectedItem.Text;
var column = gridView1.Columns.Cast<DataControlField>()
.FirstOrDefault(c => c.HeaderText == columnName);
if (column != null) column.Visible = false;
}
}
protected void gridview_rowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (DataControlField col in gvSource.Columns)
{
try
{
if (col.HeaderText == cat_check.SelectedItem.Text.Trim())
{
col.Visible = false;
}
}
catch (Exception exe)
{ }
}
}
}
Here is the simple answer.
Create css as below
.classHide{
display:none
}
then instead of col.hide,just assign classHide cssclass to the column.
e.g. col.cssclass="classHide"

Select all Checkboxes, appears selected, but are not

I'm having a strange problem, I've made a Select all checkbox, that mark as selected a lot of checkboxes.
This is the CheckedChanged event
protected void chkSelecionaTodasOcorrencias_CheckedChanged(object sender, EventArgs e)
{
if (chk_selecionaTodasOcorrencias.Checked)
{
foreach (ListItem c in chkBox_TiposOcorrencia.Items)
{
c.Selected = true;
}
}
else
{
foreach (ListItem c in chkBox_TiposOcorrencia.Items)
{
c.Selected = false;
}
}
chkBox_TiposOcorrencia.DataBind();
}
It checks all checkboxes, or uncheck all.
Then I Have another method that insert all checkedboxes in a list.
private List<int> insertItensInListIntegers(ListItemCollection itens)
{
int value = 0;
List<int> queryItens = new List<int>();
foreach (ListItem c in itens)
{
if (c.Selected) //<-- Here i'm getting false
{
tiposOcorrencias.TryGetValue(c.Text, out value);
queryItens.Add(value);
}
}
return queryItens;
}
The value informed in parameter is: chkBox_TiposOcorrencia.Items
At screen all checkboxes are cheched, but when I try debug, the c.Selected value is false.
Thanks in advance.
Like Freak_Droid was describing in his comment, if you are loading your checkboxes on pageload, simply put your code that loads your checkboxes inside an if statement checking for !ispostback. For example--
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//here is where you would put any of your code for databinding your checkboxes
}
}

ASP Is a foreach loop based on Button control on a Master page possible?

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;
}

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 ...

Resources