error "A data item was not found in the container" in the nested grid view - asp.net

In the main gridview "GridViewTtransmittals" I have the nested gridview with the name "GridViewTranstoCon".When "GridViewTranstoCon" has data, I have no problem, but when there is not any data for that it returns error "A data item was not found in the container", I like it to return null value or have it invisible.
The code is like below:
protected void GridViewTtransmittals_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem == null)
return;
TransmittaltoConPresentationModel transmittaltoCon = (TransmittaltoConPresentationModel)e.Row.DataItem;
GridView g2 = (GridView)e.Row.FindControl("GridViewTranstoCon");
if (transmittaltoCon.TranstoCons != null)
{
g2.DataSource = transmittaltoCon.TranstoCons;
g2.DataBind();
}
}
The code for data source of main gridview "GridViewTtransmittals" comes of below code:
private void DisplayTransmittals()
{
if (_Transmittals.Any())
{
var query = from transmittalno in _Transmittals
select new TransmittaltoConPresentationModel { TransID = transmittalno.TransID,
Transmittal = transmittalno.TRANSMITTAL, TranstoCons = from doctranstocon in _DocTranstoCons
where doctranstocon == null || transmittalno.TransID == doctranstocon.Transid
select doctranstocon != null ? doctranstocon.tblTranstoCon : null};
GridViewTtransmittals.DataSource = query;
}
else
{
GridViewTtransmittals.DataSource = null;
}
GridViewTtransmittals.DataBind();
}

Try to include this
protected void GridViewTtransmittals_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
}
}

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

Custom ASPxGridViewExporter

I have an aspxgridview, I change displayed text via "CustomColumnDisplayText" event, My problem is when I want to use ASPxGridViewExporter for excel output, one of columns shows wrong data. I don't know how to use ASPxGridViewExporter RenderBrick event.
protected void ASPxGridView1_CustomColumnDisplayText(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDisplayTextEventArgs e)
{
if (e.Column.PropertiesEdit.DisplayFormatString.Equals("Status"))
{
if (Convert.ToInt64(e.Value) == 2)
e.Value = "Successful";
else if (e.GetFieldValue("SaleReferenceId") == null || e.GetFieldValue("SaleReferenceId").ToString() == string.Empty || e.GetFieldValue("SaleReferenceId").ToString().Trim().Equals(""))
e.Value = "Invalid";
else if (e.GetFieldValue("saleOrderId") == null || e.GetFieldValue("saleOrderId").ToString() == string.Empty || e.GetFieldValue("saleOrderId").ToString().Trim().Equals(""))
e.Value = "Invalid";
else
e.Value = "Unsuccessful";
e.DisplayText = e.Value.ToString();
}
}
protected void ASPxGridViewExporter1_RenderBrick(object sender, DevExpress.Web.ASPxGridView.Export.ASPxGridViewExportRenderingEventArgs e)
{
// I don't know how to use it
}
I don't know how but this snippet works fine for me and the result is exactly what I wanted!
protected void ASPxGridViewExporter1_RenderBrick(object sender, DevExpress.Web.ASPxGridView.Export.ASPxGridViewExportRenderingEventArgs e)
{
try
{
GridViewDataColumn dataColumn = e.Column as GridViewDataColumn;
if (dataColumn.FieldName == "Status")
{
e.TextValue = "123";
}
}
catch (Exception ex)
{
}
}

Duplicate columns get created while clicking "Edit" in asp:GridView

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

Cant Get Data To Return To My Grid View Using Linq in ASP.NET

Not sure why but i cant get my data to return. It starts out saying there is not data records to display. But when i select the month and year of the information i am looking for the grid view disappears. Any suggestions
NutritionEntities context;
protected void Page_Load(object sender, EventArgs e)
{
context = new NutritionEntities();
if (!IsPostBack)
{
for (int i = DateTime.Now.Year; i > 1988; i--)
{
ddlYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
you have verify the binding of your control grid, i suggest add only object to the datasource of the grid on the pageLoad when the postback its false like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
}
GridView1.DataBind();
}
the problem is when you add the objects to datasource , when any event refresh the web page like select the control is unbinding, i hope help you,, see you!!

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"

Resources