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"
Related
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";
}
}
I have asp:GridView where I am using AutoGenerateEditButton="True" property to edit the grid row. Now the issue is whenever I click Edit button, the columns are populating again. For example If there 4 columns and if I click Edit than same 4 columns will reappear.
.ASPX Code:
<asp:GridView ID="grdEmpDetail" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
OnRowEditing="grdEmpDetail_RowEditing"
OnRowCancelingEdit="grdEmpDetail_RowCancelingEdit"
OnRowUpdated="grdEmpDetail_RowUpdated"
AutoGenerateEditButton="True">
</asp:GridView>
Code Behind: To Dynamically bind data on grid
protected void Page_Load(object sender, EventArgs e)
{
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
this.grdEmpDetail.AutoGenerateColumns = false;
try
{
DataTable dt = new DataTable();
dt = objBL.OrderDetail();
foreach (var col in dt.Columns)
{
if (col.ToString() == "ID" || col.ToString() == "First Name" || col.ToString() == "Last Name" || col.ToString() == "Business Phone" || col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
catch
{
throw;
}
}
Handle Edit Mode:
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
this.grdEmpDetail.DataBind();
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
this.grdEmpDetail.DataBind();
}
OUTPUT: This is fine
ISSUE : This is where I am getting issue.
What am I missing here?
You are not checking for IsPostBack in your databinding code. As a result, each time you post to the page that code is being executed again and again. So each time you will add more columns.
Modify your handler like so:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
// All of your existing code goes here
}
}
Edit
It's a little more complicated than that. You DO actually need to re-bind your DataGrid to the data source when you click edit, but you just don't want to add the columns again. This requires that you break up your code some so that the code for data-binding can be re-used without being tied to the column addition.
First, let's create a method specifically for adding columns that appear on an input DataTable:
private void AddColumnsToDataGrid(DataTable dt) {
foreach (var col in dt.Columns) {
if (col.ToString() == "ID"
|| col.ToString() == "First Name"
|| col.ToString() == "Last Name"
|| col.ToString() == "Business Phone"
|| col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
}
Next Create a Method for Databinding a DataTable to your grid:
private void DataBindGrid(DataTable dt) {
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
Now that you've extracted some of that code out, you can re-use these methods where appropriate, and only add columns one time:
Page Load Handler
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
this.grdEmpDetail.AutoGenerateColumns = false;
try {
DataTable dt = objBL.OrderDetail();
AddColumnsToDataGrid(dt);
DataBindGrid(dt);
} catch {
// Side Note: If you're just re-throwing the exception
// then the try/catch block is completely useless.
throw;
}
}
}
Editing Handlers
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
DataBindGrid(objBL.OrderDetail());
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
DataBindGrid(objBL.OrderDetail());
}
Try:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Fill_Grid();
}
}
protected Void Fill_Grid()
{
if (grdEmpDetail.Columns.Count > 0)
{
for (int n = 0; n < grdEmpDetail.Columns.Count; n++)
{
grdEmpDetail.Columns.RemoveAt(n);
}
grdEmpDetail.DataBind();
}
this.grdEmpDetail.AutoGenerateColumns = false;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
try
{
DataTable dt = new DataTable();
dt = objBL.OrderDetail();
foreach (var col in dt.Columns)
{
if (col.ToString() == "ID" || col.ToString() == "First Name" || col.ToString() == "Last Name" || col.ToString() == "Business Phone" || col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
catch (exception e1)
{
}
}
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
Fill_Grid();
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
Fill_Grid();
}
I want to hide few columns of a gridview before they gets displayed.
I want to do it by create a common function which can be used by multiple controls.
I am using an extension and would like to know how it can be done.
Here is my code
protected void btnStandardView_Click(object sender, EventArgs e)
{
_viewTypeDl = new ViewTypeDL();
DataTable dt = _viewTypeDl.GetStandardView();
gvViewType.Source(_viewTypeDl.GetStandardView(),"ColorCode");
ViewState["request"] = "Standard View";
}
public static void Source(this CompositeDataBoundControl ctrl, DataTable dt, params string[] ColumnsToHide)
{
ctrl.DataSource = dt;
ctrl.DataBound += new GridViewRowEventHandler(ctrl_DataBound);
ctrl.DataBind();
}
static void ctrl_DataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells["ColorCode"].Visible = false;
}
I want to create an extension to hide or show columns provided in the list as an array.
1st function is used on page. While below two functions are needs to be used for multiple applications
There are two ways you can meet your requirement.
set gvViewType.Columns[i].visble = false;
Allow css to handle the hidden columns for you.
.hidden
{
display:none;
}
.visble
{
display:block;
}
//This is the Gridview event.
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Cells Represent the Column
e.Row.Cells[0].CssClass = "hidden";
}
else if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].CssClass = "hidden";
}
}
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
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; }
}
}