Row Group Issue in Row Background Color - devexpress

I have a Devexpress Xtragrid, with in which I grouped rows based on a particular column. I have given Dark blue back color to the Group and set ShowGroupExpandCollpaseButton as false as well. In the left most part of each child rows in the grid is displaying the color I set to the Group back color. Is there any way to remove this color?

To accomplish this task, please remove the BackColor from the GroupRow appearance.
Then use the CustomDrawGroupRow event to highlight the group row content as you need:
// 1) remove GroupRow style
//gridView1.Appearance.GroupRow.BackColor = Color.Blue;
gridView1.OptionsView.ShowGroupExpandCollapseButtons = false;
// 2) use the CusomDrawGroupRow
gridView1.CustomDrawGroupRow += gridView1_CustomDrawGroupRow;
}
void gridView1_CustomDrawGroupRow(object sender, RowObjectCustomDrawEventArgs e) {
GridView gridView = sender as GridView;
GridGroupRowInfo groupRowInfo = e.Info as GridGroupRowInfo;
string groupRowText = gridView.GetGroupRowDisplayText(e.RowHandle);
int textStart = groupRowInfo.DataBounds.Left + 4;
Rectangle groupRowTextBounds = new Rectangle(
textStart,
groupRowInfo.Bounds.Top,
groupRowInfo.Bounds.Right - textStart,
groupRowInfo.Bounds.Height
);
e.Cache.FillRectangle(Brushes.Blue, e.Bounds); // draw blue backgrownd
e.Appearance.DrawString(e.Cache, groupRowText, groupRowTextBounds);
e.Handled = true;
}

You should be able to hide the group from the view by setting as follows:
this.gridView1.OptionsView.ShowGroupedColumns = false;

Download the [project][1](https://drive.google.com/file/d/13XkT9qsqwFP-f2sPID70T2y2fSrs4Gp0/view?usp=sharing) or follow the below steps.
Grid:
Excel Download
Getdata
private DataTable getTestData()
{
///Step 1: Getdata from Db
DataTable dt = new DataTable();
dt.Columns.Add("GROUPCOLUMN");
dt.Columns.Add("PRODUCTGROUPID");
dt.Columns.Add("SIZEID");
dt.Columns.Add("SHAPEID");
dt.Columns.Add("COLORID");
dt.Columns.Add("CLARITYID");
dt.Columns.Add("CARAT", typeof(decimal));
dt.Columns.Add("QTY", typeof(Int32));
dt.Columns.Add("GROUPLEVEL", typeof(Int32));
dt.Columns.Add("AVGCARAT", typeof(decimal));
dt.Rows.Add("", "POLISH", "0.30-0.39", "BR", "D", "IF", 0.30, 1, 0, 0.30);
dt.Rows.Add("", "POLISH", "0.40-0.49", "BR", "D", "IF", 0.40, 1, 0, 0.30);
dt.Rows.Add("", "POLISH", "0.40-0.49", "BR", "D", "VVS1", 0.40, 1, 0, 0.30);
dt.Rows.Add("", "POLISH", "0.30-0.39", "BR", "D", "VVS2", 0.30, 1, 0, 0.30);
dt.Rows.Add("", "S.PRECIOUS", "0.30-0.39", "BR", "D", "IF", 0.30, 1, 0, 0.30);
dt.Rows.Add("", "S.PRECIOUS", "0.30-0.39", "BR", "D", "IF", 0.30, 1, 0, 0.30);
dt.Rows.Add("", "COLOR", "0.30-0.39", "BR", "D", "IF", 0.30, 1, 0, 0.30);
dt.Rows.Add("", "COLOR", "0.30-0.39", "BR", "D", "IF", 0.30, 1, 0, 0.30);
return dt;
}
Create GridView Event (gridView1_GroupLevelStyle) for displaying grid data color
private void gridView1_GroupLevelStyle(object sender, GroupLevelStyleEventArgs e)
{
///Step 2: Create GridView Event (gridView1_GroupLevelStyle) for displaying grid data color
e.LevelAppearance.ForeColor = getForeGroupColor(e.Level);
e.LevelAppearance.BackColor = getBackGroupColor(e.Level);
}
Create method getBackGroupColor(Group Index), getForeGroupColor(GroupIndex) in C# Code
public Color getBackGroupColor(Int32 groupLevel)
{
Color groupColor = Color.White;
if (groupLevel == 0)
{
groupColor = Color.Salmon;
}
else if (groupLevel == 1)
{
groupColor = Color.Green;
}}
Most Important Create Gridview Event (gridView1_CustomSummaryCalculate) and set group level into the GroupLevel Column SummaryItem(Follow the instruction as given the comment on to the method)
///Step 4: Most Important Create Gridview Event (gridView1_CustomSummaryCalculate) and set group level into the GroupLevel Column SummaryItem(Follow the instruction as given the comment on to the method)
private void gridView1_CustomSummaryCalculate(object sender, DevExpress.Data.CustomSummaryEventArgs e)
{
if (e.IsGroupSummary)
{
switch (e.SummaryProcess)
{
case CustomSummaryProcess.Start:
break;
case CustomSummaryProcess.Calculate:
break;
case CustomSummaryProcess.Finalize:
if (((DevExpress.XtraGrid.GridSummaryItem)e.Item).FieldName == "GROUPLEVEL")
{
///set Group level into the grouplevel summary
e.TotalValue = e.GroupLevel;
}
break;
}
}
}
Create button for export grid data and write code as writen into the method
Like
try
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel Workbook|*.xlsx|Excel 97-2003 Workbook|*.xls";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.FileName = String.Format("Test_{0}.xlsx", DateTime.Now.ToString("ddMMMyyyyhhmmss"));
DialogResult res = saveFileDialog1.ShowDialog();
if (res == DialogResult.Cancel)
return;
XlsxExportOptionsEx exportOptions = new XlsxExportOptionsEx();
exportOptions.CustomizeCell += exportOptions_CustomizeCell;
this.gridView1.ExportToXlsx(saveFileDialog1.FileName, exportOptions);
System.Diagnostics.Process.Start(saveFileDialog1.FileName);
}
catch (Exception ex)
{ }
Create Method(Event) exportOptions_CustomizeCell
private void exportOptions_CustomizeCell(CustomizeCellEventArgs e)
{
if (e.RowHandle < 0)
{
///Export excel set Group color
DevExpress.XtraGrid.GridGroupSummaryItem SummaryItem = this.gridView1.GroupSummary.Where(x => x.FieldName == "GROUPLEVEL").ToList()[0] as DevExpress.XtraGrid.GridGroupSummaryItem;
Int32 groupLevel = Convert.ToInt32(this.gridView1.GetGroupSummaryValue(e.RowHandle, SummaryItem));
e.Formatting.BackColor = getBackGroupColor(groupLevel);
}
///Set Header Column setting(BackColor, ForeColor, Font Style)
else if (e.DataSourceRowIndex == -1)
{
e.Formatting.BackColor = Color.Black;
e.Formatting.Font.Color = Color.White;
e.Formatting.Font.Italic = true;
}
e.Handled = true;
}

Related

The OnEndPage event and a table with a RowSpan

I added the creation of a table cone page header in OnEndPage. In table I a RowSpan that is not printed, while the rest is.
table.WriteSelectedRows (0, -1, pageSize.GetLeft (25), pageSize.GetTop (10), cb);
If I remove the RowSpan prints!
This is the code I use:
public override void OnEndPage(PdfWriter writer, Document document)
{
if (document.PageNumber != 1)
{
if (report.repeatHead) //ripete l'intestazione del report su tutte le pagine di stampa
{
repeatHead(writer, document);
}
else
{
if (document.PageNumber == 2) //ripete l'intestazione del report solo sulla second pagina dopo la copertina
{
repeatHead(writer, document);
}
}
}
}
public void repeatHead(PdfWriter writer, Document document)
{
//OnStartPage
base.OnStartPage(writer, document);
Rectangle pageSize = document.PageSize;
PdfPTable table = new PdfPTable(2);
//table.WidthPercentage = 100;
table.TotalWidth = pageSize.Width - 50;
table.DefaultCell.Border = Rectangle.NO_BORDER;
//impostazione larghezza celle
iTextSharp.text.Rectangle rect = PageSize.A4;
float pageWidth = rect.Width;
table.SetWidthPercentage(new float[]
{
(float).70 * pageWidth ,
(float).30 * pageWidth,
}, rect);
//Cella nome banca
table.AddCell(CellTest(report.banca, 1, 2));
//Cella descrizione indagine
table.AddCell(CellTest("Valore1", 0, 0));
//Cella data apertura
table.AddCell(CellTest("Data apertura: " + DateTime.Now, 0, 0));
//Cella descrizione
table.AddCell(CellTest("Descrizione", 0, 0));
//Cella data chiusura
table.AddCell(CellTest("Data chiusura: " + DateTime.Now, 0, 0));
table.WriteSelectedRows(0, -1, pageSize.GetLeft(25), pageSize.GetTop(10), cb);
}
private PdfPCell CellTest(string value, int colSpan, int rowSpan)
{
iTextSharp.text.Font font = FontFactory.GetFont("Arial");
PdfPCell c = new PdfPCell(new Phrase(value, font));
c.BorderWidthLeft = 1f;
c.BorderWidthTop = 1f;
c.BorderWidthRight = 1f;
c.BorderWidthBottom = 1f;
if (rowSpan != 0) { c.Rowspan = rowSpan; }
if (colSpan != 0) { c.Colspan = colSpan; }
return c;
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
template.BeginText();
template.SetFontAndSize(bf, 8);
template.SetTextMatrix(0, 0);
template.ShowText("" + (writer.PageNumber - 1));
template.EndText();
}

Assigning data from e.Row.DataItem

As i am new to asp i have a small problem regarding assigning based on e.Row.DataItem.
code:
protected void grdStaffReport_RowDataBound(object sender, GridViewRowEventArgs e)
{
ApplicationRegistration appReg = new ApplicationRegistration();
if (e.Row.RowType == DataControlRowType.DataRow)
{
All_Ticket allTicket = e.Row.DataItem as All_Ticket;
if (allTicket != null)
{
Label lblTicketId = ((Label)e.Row.FindControl("lblTicketId"));
lblTicketId.Text = "PHDT" + allTicket.TicketId;
Label lblStartedBy = ((Label)e.Row.FindControl("lblStartedBy"));
lblStartedBy.Text = this.GetTicketStartBy(allTicket.ClientId);
HyperLink hylnk = (HyperLink)e.Row.FindControl("HyperLink1");
hylnk.NavigateUrl = "~/User/DisplayTicket.aspx?TicketId=" + allTicket.TicketId + " &AppId=" + allTicket.AppId;
Label lblIsCloesed = ((Label)e.Row.FindControl("lblIsCloesed"));
if (allTicket.isClosed == true)
{
hylnk.ForeColor = System.Drawing.Color.Green;
lblIsCloesed.Text = "Yes";
}
else
{
lblIsCloesed.Text = "No";
hylnk.ForeColor = System.Drawing.Color.Blue;
}
Label lblLastUpdateBy = ((Label)e.Row.FindControl("lblLastUpdateBy"));
lblLastUpdateBy.Text = this.GetTicketLastUpdateBy(allTicket.TicketId, lblStartedBy.Text);
TicketRegistration ticReg = new TicketRegistration();
Ticket_Reply tic = ticReg.GetMaxTicketByTicketId(allTicket.TicketId);
Label lblUpdationDt = (Label)e.Row.FindControl("lblUpdationDt");
Label lblclient = (Label)e.Row.FindControl("lblClint");
var user = userManage.GetClientUserByUserId(allTicket.ClientId);
lblclient.Text = _clientReg.GetClientNameByID(user.ParentId);
if (tic != null)
{
lblUpdationDt.Text = Convert.ToString(tic.CreationDt);
}
else
{
lblUpdationDt.Text = Convert.ToString(allTicket.CreationDt);
}
Label lblAppId = ((Label)e.Row.FindControl("lblApplicaton"));
lblAppId.Text = appReg.GetAppNameByID(allTicket.AppId);
Label lblSNo = ((Label)e.Row.FindControl("lblSno"));
lblSNo.Text = (++i).ToString();
}
}
}
Note: Here e.Row.DataItem has data(seen by placing breakpoint),but when this is executed allTicket is not assigned any data.
please revert the solution

How to bind database using LIST?

Hi iam try to Get Database data and showed in RadTreeview,
here i got one sample,that sample like default sample,every Root and Child has to be enter manually,
but i want bind from database,values are filled automatically(root/child)
i will show that example code,
List<SiteDataItem> siteData = new List<SiteDataItem>();
siteData.Add(new SiteDataItem(1, 0, "Products"));
siteData.Add(new SiteDataItem(2, 1, "RadControls for ASP.NET Ajax"));
siteData.Add(new SiteDataItem(3, 1, "RadControls for Silverlight"));
siteData.Add(new SiteDataItem(4, 2, "RadGrid"));
siteData.Add(new SiteDataItem(5, 2, "RadScheduler"));
siteData.Add(new SiteDataItem(6, 2, "RadEditor"));
siteData.Add(new SiteDataItem(7, 3, "RadGrid"));
siteData.Add(new SiteDataItem(8, 3, "RadMenu"));
siteData.Add(new SiteDataItem(9, 3, "RadEditor"));
RadTreeView1 .DataTextField = "Text";
RadTreeView1.DataFieldID = "ID";
RadTreeView1.DataFieldParentID = "ParentID";
RadTreeView1.DataSource = siteData;
RadTreeView1.DataBind();
Please help me to do as i want
Please try with the below code snippet.
protected void Page_Load(object sender, System.EventArgs e)
{
List<TestModels> models = new List<TestModels>();
models.Add(new TestModels() { ID = 1, ParentID = null, Text = "a1" });
models.Add(new TestModels() { ID = 2, ParentID = 1, Text = "a2" });
models.Add(new TestModels() { ID = 3, ParentID = 2, Text = "a3" });
models.Add(new TestModels() { ID = 4, ParentID = null, Text = "a4" });
models.Add(new TestModels() { ID = 5, ParentID = 4, Text = "a5" });
RadTreeView1.DataTextField = "Text";
RadTreeView1.DataFieldID = "ID";
RadTreeView1.DataFieldParentID = "ParentID";
RadTreeView1.DataSource = models;
RadTreeView1.DataBind();
}
Class
public class TestModels
{
public int ID { get; set; }
public int? ParentID { get; set; }
public string Text { get; set; }
}
Please Set NULL in ParentID in place-of 0.
Because It consider 0 as value. RadTreeView is not able to found any ID field which have 0 value.
You can try something like this.
DataTable data= GetDataFromDatabase()
RadTreeView1.DataTextField = "TextFieldwhichyouwantshow";
RadTreeView1.DataFieldID = "IDFromdatabase";
RadTreeView1.DataFieldParentID = "ParentIDFromDatabase";
RadTreeView1.DataSource = data;
RadTreeView1.DataBind();

Get variable from one method and use as a private string

I was really hoping someone could help me,
I need to get the variable product from the method GridView1_RowDataBound to the quote value class string product.
Its for a pdf creator and any help would be greatly appreciated as i've been stuck on this for quite a while, please excuse as I'm fairly inexperienced in .net.
Thanks very much!!
enter code here
public partial class quotedetail : System.Web.UI.Page
{
private string quoteId;
private string product;
private string connectId = "";
string description = "Save Your Quote as a PDF with your Company Logo and Print out for Customers";
public string ConnectId { get { return connectId; } }
protected void Page_Init(object sender, EventArgs e)
{
connectId = Global.GetConnectionString();
quoteId = Request.QueryString["quote"];
product =
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
(Master as WebOnlineMasterPage).PageTitle = "Quote - " + quoteId;
DisplayPage();
}
}
protected void DisplayPage()
{
try
{
DataSet ds = new WebOnlineQuote.Quote().GetQuote(ConnectId, quoteId);
FormView1.DataSource = ds.Tables[0];
GridView1.DataSource = ds.Tables[1];
Page.DataBind();
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Global.CheckException(ex);
description = "Sorry, information about this quote is unavailable.";
Panel1.Visible = false;
}
(Master as WebOnlineMasterPage).PageDescription = description;
}
public void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
e.Row.Attributes.Add("onmouseover", "className='dataOver'");
if (e.Row.DataItemIndex % 2 == 1)
e.Row.Attributes.Add("onmouseout", "className='dataAltRow'");
else
e.Row.Attributes.Add("onmouseout", "className='data'");
string product = ((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString();
e.Row.Attributes.Add("onClick", String.Format("document.location='productdetail.aspx?id={0}'", product));
}
}
protected void FormView1_DataBound(object sender, EventArgs e)
{
// get the expiry date
bool isopen = (bool)((DataRow)((DataRowView)FormView1.DataItem).Row)["IsOpen"];
bool expired = (bool)((DataRow)((DataRowView)FormView1.DataItem).Row)["Expired"];
int viewIndex = 0;
if (isopen && !expired)
viewIndex = 1;
// set appropriate view
MultiView view = (MultiView)FormView1.FindControl("QuoteProcessView");
view.ActiveViewIndex = viewIndex;
}
protected void AcceptQuote_Btn_Click(object sender, EventArgs e)
{
Response.Redirect("checkout.aspx?quote=" + quoteId);
}
protected void Requote_Btn_Click(object sender, EventArgs e)
{
Response.Redirect("requestquote.aspx?quote=" + quoteId);
}
// ********************PDF Start********************
protected void SaveAsPdf_Click(object sender, EventArgs e)
{
DataSet quote = new WebOnlineQuote.Quote().GetQuote(ConnectId, quoteId);
Document document = CreateDocument();
PdfDocumentRenderer renderer = new PdfDocumentRenderer();
renderer.Document = document;
renderer.RenderDocument();
MemoryStream ms = new MemoryStream();
renderer.PdfDocument.Save(ms);
byte[] pdfBytes = ms.ToArray();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=quote.pdf");
Response.AddHeader("Content-Length", pdfBytes.Length.ToString());
Response.BinaryWrite(pdfBytes);
Response.StatusCode = 200;
Response.End();
}
public Document CreateDocument()
{
Document document = new Document();
document.Info.Title = "A sample invoice";
document.Info.Subject = "Demonstrates how to create an invoice.";
DefineStyles(document);
TextFrame addressFrame;
MigraDoc.DocumentObjectModel.Tables.Table table;
CreatePage(document, out addressFrame, out table );
FillContent(document, addressFrame, table);
return document;
}
void DefineStyles(Document document)
{
// Get the predefined style Normal.
MigraDoc.DocumentObjectModel.Style style = document.Styles["Normal"];
// Because all styles are derived from Normal, the next line changes the
// font of the whole document. Or, more exactly, it changes the font of
// all styles and paragraphs that do not redefine the font.
style.Font.Name = "Verdana";
style = document.Styles[StyleNames.Header];
style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);
style = document.Styles[StyleNames.Footer];
style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);
// Create a new style called Table based on style Normal
style = document.Styles.AddStyle("Table", "Normal");
style.Font.Name = "Verdana";
style.Font.Name = "Times New Roman";
style.Font.Size = 9;
// Create a new style called Reference based on style Normal
style = document.Styles.AddStyle("Reference", "Normal");
style.ParagraphFormat.SpaceBefore = "5mm";
style.ParagraphFormat.SpaceAfter = "5mm";
style.ParagraphFormat.TabStops.AddTabStop("16cm", TabAlignment.Right);
}
void CreatePage(Document document, out TextFrame addressFrame, out MigraDoc.DocumentObjectModel.Tables.Table table)
{
// Each MigraDoc document needs at least one section.
Section section = document.AddSection();
// Put a logo in the header
MigraDoc.DocumentObjectModel.Shapes.Image image = section.Headers.Primary.AddImage(Server.MapPath("~/images/cnwlogo.jpg"));
image.Height = "2.5cm";
image.LockAspectRatio = true;
image.RelativeVertical = RelativeVertical.Line;
image.RelativeHorizontal = RelativeHorizontal.Margin;
image.Top = ShapePosition.Top;
image.Left = ShapePosition.Right;
image.WrapFormat.Style = WrapStyle.Through;
// Create footer
Paragraph paragraph = section.Footers.Primary.AddParagraph();
paragraph.AddText("PowerBooks Inc · Sample Street 42 · 56789 Cologne · Germany");
paragraph.Format.Font.Size = 9;
paragraph.Format.Alignment = ParagraphAlignment.Center;
// Create the text frame for the address
addressFrame = section.AddTextFrame();
addressFrame.Height = "3.0cm";
addressFrame.Width = "7.0cm";
addressFrame.Left = ShapePosition.Left;
addressFrame.RelativeHorizontal = RelativeHorizontal.Margin;
addressFrame.Top = "5.0cm";
addressFrame.RelativeVertical = RelativeVertical.Page;
// Put sender in address frame
paragraph = addressFrame.AddParagraph("PowerBooks Inc · Sample Street 42 · 56789 Cologne");
paragraph.Format.Font.Name = "Times New Roman";
paragraph.Format.Font.Size = 7;
paragraph.Format.SpaceAfter = 3;
// Add the print date field
paragraph = section.AddParagraph();
paragraph.Format.SpaceBefore = "8cm";
paragraph.Style = "Reference";
paragraph.AddFormattedText("INVOICE", TextFormat.Bold);
paragraph.AddTab();
paragraph.AddText("Cologne, ");
paragraph.AddDateField("dd.MM.yyyy");
// Create the item table
table = section.AddTable();
table.Style = "Table";
table.Borders.Color = Colors.DarkBlue;
table.Borders.Width = 0.25;
table.Borders.Left.Width = 0.5;
table.Borders.Right.Width = 0.5;
table.Rows.LeftIndent = 0;
// Before you can add a row, you must define the columns
Column column = table.AddColumn("3cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("5cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("1cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("1cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("2cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("2cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("2cm");
column.Format.Alignment = ParagraphAlignment.Right;
// Create the header of the table
CreateHeaderRow(table);
table.SetEdge(0, 0, 7, 1, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75, Color.Empty);
//create data table
}
private static void CreateHeaderRow(MigraDoc.DocumentObjectModel.Tables.Table table)
{
Row headerRow1 = table.AddRow();
headerRow1.HeadingFormat = true;
headerRow1.Format.Alignment = ParagraphAlignment.Center;
headerRow1.Format.Font.Bold = true;
headerRow1.Shading.Color = Colors.AliceBlue;
headerRow1.Cells[0].AddParagraph("PRODUCT");
headerRow1.Cells[0].Format.Font.Bold = false;
headerRow1.Cells[0].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[0].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[0].MergeDown = 1;
headerRow1.Cells[1].AddParagraph("DESCRIPTION");
headerRow1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[1].MergeDown = 1;
headerRow1.Cells[2].AddParagraph("QTY");
headerRow1.Cells[2].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[2].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[2].MergeDown = 1;
headerRow1.Cells[3].AddParagraph("UNIT");
headerRow1.Cells[3].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[3].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[3].MergeDown = 1;
headerRow1.Cells[4].AddParagraph("PRICE");
headerRow1.Cells[4].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[4].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[4].MergeDown = 1;
headerRow1.Cells[5].AddParagraph("TAX");
headerRow1.Cells[5].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[5].MergeDown = 1;
headerRow1.Cells[6].AddParagraph("TOTAL");
headerRow1.Cells[6].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[6].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[6].MergeDown = 1;
}
class QuoteItemRow
{
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
e.Row.Attributes.Add("onmouseover", "className='dataOver'");
if (e.Row.DataItemIndex % 2 == 1)
e.Row.Attributes.Add("onmouseout", "className='dataAltRow'");
else
e.Row.Attributes.Add("onmouseout", "className='data'");
string product = ((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductID"].ToString();
e.Row.Attributes.Add("onClick", String.Format("document.location='productdetail.aspx?id={0}'", product));
}
}
public QuoteItemRow(decimal quantity, decimal price, decimal discount, string itemNumber, string title)
{
Quantity = quantity;
Price = price;
Discount = discount;
ItemNumber = itemNumber;
Title = title;
}
public decimal Quantity;
public decimal Discount;
public decimal Price;
public string ItemNumber;
public string Title;
}
void FillContent(Document document, TextFrame addressFrame, MigraDoc.DocumentObjectModel.Tables.Table table)
{
Paragraph paragraph = addressFrame.AddParagraph();
paragraph.AddText("Joe Bloggs");
paragraph.AddLineBreak();
paragraph.AddText("12 Some St");
paragraph.AddLineBreak();
paragraph.AddText(product);
// Iterate the invoice items
decimal totalExtendedPrice = 0;
QuoteItemRow[] items = new QuoteItemRow[] {
new QuoteItemRow (2.0m, 3.4m, 0.2m, "3213421", product ),
new QuoteItemRow (2.4m, 3.4m, 0.0m, "3534DD21", quoteId ),
new QuoteItemRow (8, 0.4m, 0.1m, "908587", quoteId ),
};
foreach (QuoteItemRow item in items)
{
decimal quantity = item.Quantity;
decimal price = item.Price;
decimal discount = item.Discount;
// Each item fills two rows
Row row1 = table.AddRow();
Row row2 = table.AddRow();
row1.TopPadding = 1.5;
row1.Cells[0].Shading.Color = Colors.LightGray;
row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
row1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[2].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[3].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[4].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[5].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[6].Format.Alignment = ParagraphAlignment.Left;
paragraph = row1.Cells[1].AddParagraph();
paragraph.AddFormattedText(item.Title, TextFormat.Bold);
row2.Cells[1].AddParagraph(item.Quantity.ToString());
row2.Cells[2].AddParagraph("$" + price.ToString("0.00"));
row2.Cells[3].AddParagraph("$" + discount.ToString("0.0"));
row2.Cells[4].AddParagraph();
row2.Cells[5].AddParagraph("$" + price.ToString("0.00"));
decimal extendedPrice = quantity * price;
extendedPrice = extendedPrice * (100 - discount) / 100;
row1.Cells[5].AddParagraph("$" + extendedPrice.ToString("0.00"));
row1.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
totalExtendedPrice += extendedPrice;
table.SetEdge(0, table.Rows.Count - 2, 6, 2, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75);
}
// Add an invisible row as a space line to the table
Row row = table.AddRow();
row.Borders.Visible = false;
// Add the total price row
row = table.AddRow();
row.Cells[0].Borders.Visible = false;
row.Cells[0].AddParagraph("Total Price");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");
// Add the VAT row
row = table.AddRow();
row.Cells[0].Borders.Visible = false;
row.Cells[0].AddParagraph("VAT (19%)");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
row.Cells[5].AddParagraph((0.19m * totalExtendedPrice).ToString("0.00") + " €");
// Add the additional fee row
row = table.AddRow();
row.Cells[0].Borders.Visible = false;
row.Cells[0].AddParagraph("Shipping and Handling");
row.Cells[5].AddParagraph(0.ToString("0.00") + " €");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
// Add the total due row
row = table.AddRow();
row.Cells[0].AddParagraph("Total Due");
row.Cells[0].Borders.Visible = false;
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
totalExtendedPrice += 0.19m * totalExtendedPrice;
row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");
// Set the borders of the specified cell range
table.SetEdge(5, table.Rows.Count - 4, 1, 4, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75);
// Add the notes paragraph
paragraph = document.LastSection.AddParagraph();
paragraph.Format.SpaceBefore = "1cm";
paragraph.Format.Borders.Width = 0.75;
paragraph.Format.Borders.Distance = 3;
paragraph.Format.Borders.Color = Colors.DarkBlue;
paragraph.Format.Shading.Color = Colors.LightGray;
}
}
Easiest solution would be to put the value in a Session
Session.Add("ProductCode", ((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString());
To get the value:
Session["ProductCode"].ToString()
Keep in mind though that you are doing this in the item databound, in the event that you are expecting multiple values for product code, I would suggest storing the values in a collection prior to putting it in the Session.
i.e.
if(Session["ProductCode"] != null)
{
List<string> pcodes = Session["ProductCode"] as List<string>();
pcodes.Add(((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString());
Session.Add("ProductCode", pcodes);
}
else
{
List<string> pcodes = new List<string>();
pcodes.Add(((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString());
Session.Add("ProductCode", pcodes);
}
To get the values:
Session["ProductCode"] as List<string>()

Argument out of Exception unhandled in MigraDoc

static void Main(string[] args)
{
string saveFileAs = "D:\\Hello.pdf";
Program p = new Program();
Document doc = p.CreateDocument();
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
renderer.Document = doc;
renderer.RenderDocument();
renderer.PdfDocument.Save("D:\\Hello.pdf");
Process.Start(saveFileAs);
}
public Document CreateDocument()
{
// Create a new MigraDoc document
this.document = new Document();
this.document.Info.Title = "A sample invoice";
this.document.Info.Subject = "Demonstrates how to create an invoice.";
this.document.Info.Author = "Chandana Amarnath";
DefineStyles();
CreatePage();
FillContent();
return this.document;
}
void CreatePage()
{
// Each MigraDoc document needs at least one section.
Section section = this.document.AddSection();
// Put a logo in the header
Image image = section.Headers.Primary.AddImage("D:\\Cubes.jpg");
image.Height = "2.5cm";
image.LockAspectRatio = true;
image.RelativeVertical = RelativeVertical.Line;
image.RelativeHorizontal = RelativeHorizontal.Margin;
image.Top = ShapePosition.Top;
image.Left = ShapePosition.Right;
image.WrapFormat.Style = WrapStyle.Through;
// Create footer
Paragraph paragraph = section.Footers.Primary.AddParagraph();
// The following one prints at the footer;
paragraph.AddText("Aldata Inc.");
paragraph.Format.Font.Size = 9;
paragraph.Format.Alignment = ParagraphAlignment.Center;
// Create the text frame for the address
this.addressFrame = section.AddTextFrame();
this.addressFrame.Height = "3.0cm";
this.addressFrame.Width = "7.0cm";
this.addressFrame.Left = ShapePosition.Left;
this.addressFrame.RelativeHorizontal = RelativeHorizontal.Margin;
this.addressFrame.Top = "5.0cm";
this.addressFrame.RelativeVertical = RelativeVertical.Page;
// Put sender in address frame
paragraph = this.addressFrame.AddParagraph("Aldata-Apollo Inc.");
paragraph.Format.Font.Name = "Times New Roman";
paragraph.Format.Font.Size = 7;
paragraph.Format.SpaceAfter = 3;
// Add the print date field
paragraph = section.AddParagraph();
paragraph.Format.SpaceBefore = "8cm";
paragraph.Style = "Reference";
paragraph.AddFormattedText("Section Comparator", TextFormat.Bold);
paragraph.AddTab();
paragraph.AddText("Date: ");
paragraph.AddDateField("dd.MM.yyyy");
// Create the item table
this.table = section.AddTable();
this.table.Style = "Table";
this.table.Borders.Color = Color.Parse("Black");
this.table.Borders.Width = 0.25;
this.table.Borders.Left.Width = 0.5;
this.table.Borders.Right.Width = 0.5;
this.table.Rows.LeftIndent = 0;
//************ Before you can add a row, you must define the columns **********
Column column = this.table.AddColumn("4cm");
column.Format.Alignment = ParagraphAlignment.Center;
column = this.table.AddColumn("3cm");
column.Format.Alignment = ParagraphAlignment.Right;
// Create the header of the table
Row row = table.AddRow();
row.HeadingFormat = true;
row.Format.Alignment = ParagraphAlignment.Center;
row.Format.Font.Bold = true;
row.Shading.Color = Color.Parse("White");
row.Cells[0].AddParagraph("Added");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Center;
row.Cells[0].MergeRight = 3;
row = table.AddRow();
row.HeadingFormat = true;
row.Format.Alignment = ParagraphAlignment.Center;
row.Format.Font.Bold = true;
row.Cells[0].AddParagraph("Deleted Items");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Left;
row.Cells[0].MergeRight = 3;
this.table.SetEdge(0, 0, 2, 3, Edge.Box, BorderStyle.Single, 0.75, Color.Empty);
}
void FillContent()
{
string xmlFileName = "C:\\Section.xml";
XPathDocument xPathDocument = new XPathDocument(xmlFileName);
XPathNavigator item = xPathDocument.CreateNavigator();
XPathNodeIterator iter = item.Select("/Hello/*");
while (iter.MoveNext())
{
string name = iter.Current.Name;
item = iter.Current;
Row row1 = this.table.AddRow();
Row row2 = this.table.AddRow();
row1.TopPadding = 1.5;
row1.Cells[0].Shading.Color = Color.Parse("Gray");
row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
row1.Cells[0].MergeDown = 1;
row1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[1].MergeRight = 3;
row1.Cells[0].AddParagraph(item.ToString());
Console.WriteLine(name + "\t:" +item);
}
Console.ReadKey();
}
I am writing code for generating my report in PDF using MigraDoc. I have downloaded the code from PDFSharp site. The following has 3 functions DefineStyles(), CreatePage(), FillContent(). I made changes in function CreatePage(), FillContent(); But when I am running the program I am getting error saying
Argument out of Exception:
Specified argument was out of the range of valid values.
In the CreatePage() I added 2 rows and 2 columns to a table. And in the FillContent() function I read my XML file. But I am unable to find where I am crossing my index range.
SOLVED
The problem is when I am setting the table.SetEdge(...). I am accessing the columns that I have not created.
Thank u all .. :)
At this step I was setting the rows that are not yet created.
this.table.SetEdge(0, 0, 2, 3, Edge.Box, BorderStyle.Single, 0.75, Color.Empty);
Instead of 3 which are the number of rows I should use 2.

Resources