subtract label values in asp.net - asp.net

I want to subtract number from Label on button click.When i do that on button click values is subtracted just once, and on second click on the same button nothing is happen.I cannot figure out what is the problem?-Here is my code:
protected void btnTest_Click(object sender, EventArgs e)
{
Session["Counter"] = newValue;
if (ViewState["Markici"] != null)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
ViewState["Markici"] = dtCurrentTable;
dtCurrentTable = (DataTable)ViewState["Markici"];
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
decimal old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int32>("TarifaID");
decimal newIznos = oldIznos - Convert.ToDecimal(Cena1);
dtCurrentTable.Rows[clickedIndex].SetField("Kolicina", newValue.ToString());
dtCurrentTable.Rows[clickedIndex].SetField("VkIznos", newIznos.ToString());
//Here i do the operation
decimal minus = Convert.ToDecimal(Label42.Text) - Convert.ToDecimal(Cena1);
Label26.Text = minus.ToString();
}

All the time I was subtracting in wrong label..
decimal minus = Convert.ToDecimal(Label42.Text) - Convert.ToDecimal(Cena1);
Label42.Text = minus.ToString();

Related

I am creating an application in windows form

I want to add labels through loop
`private void CourseOutcomes_Load(object sender, EventArgs e)
{
studentDetails dets = new studentDetails();
dets.ShowDialog();
name=dets.CourseName;
labelCourseName.Text = name;
string id = dets.CourseValue;
SqlDataReader sdr = bznessLogic.GetQuestions(id);
List<Label> lbl = new List<Label>();
int count = 0;
while (sdr.Read())
{
MessageBox.Show("s");
lbl[count] = new Label();
lbl[count].Text = sdr[0].ToString();
this.Controls.Add(lbl[count]);
count++;
}
sdr.Close();
}`
But it keeps giving error
'Index was out of range.
Should I initiablize it diffrently or..
So it turns out I just needed to initialize it properly which I expected, noob mistake but here we are.
private void CourseOutcomes_Load(object sender, EventArgs e)
{
studentDetails dets = new studentDetails();
dets.ShowDialog();
name=dets.CourseName;
labelCourseName.Text = name;
string id = dets.CourseValue;
SqlDataReader sdr = bznessLogic.GetQuestions(id);
List<Label> lbl = new List<Label>();
int count = 0;
while (sdr.Read())
{
MessageBox.Show("s");
lbl.Add(new Label() { Name="lbl"+count});
lbl[count].Text = sdr[0].ToString();
this.Controls.Add(lbl[count]);
count++;
}
sdr.Close();
}

pass parameter value from one method to another aspx.net

I need help here. Below is my code. In this line of code
dtCurrentTable.Rows[0]["Kolicina"] = Convert.ToInt32(Label37.Text) + 3;
instead of 3 in next method this Label37.Text value should be incremented for one each time when user press the button.So I want this label value in next method to start to count from current value for one each time on button click.
protected void btnTest_Click(object sender, EventArgs e)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
decimal old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int16>("TarifaID");
newValue = old - 1;
// so i need label value from here to go in next method and increment++
Label37.Text = newValue.ToString();
decimal newIznos = oldIznos - Convert.ToDecimal(Cena1);
dtCurrentTable.Rows[clickedIndex].SetField("Kolicina", newValue.ToString());
dtCurrentTable.Rows[clickedIndex].SetField("VkIznos", newIznos.ToString());
}
protected void Button6_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["string2"].ConnectionString);
conn.Open();
ViewState["count"] = Convert.ToInt32(ViewState["count"]) + 1;
// SqlCommand sqlCmd = new SqlCommand();
// sqlCmd.CommandText = "SupaSpanak";
// sqlCmd.Connection = conn;
// sqlCmd.CommandType = CommandType.StoredProcedure;
SqlCommand cmd1 = new SqlCommand("SELECT pkid,Artikal,Vid,EdMera,TarifaID,Cena1 FROM Artikli WHERE Artikal= 'N KREM SUPA OD SPANA]++' AND Cena1 = 130.00", conn);
//brojac za kolicina
count++;
decimal noofcount = count;
Session["kolicina"] = noofcount;
Label5.Text = Session["kolicina"].ToString();//ViewState["count"].ToString();//
SqlDataReader reader = cmd1.ExecuteReader();
if (reader.Read())
{
Label9.Text = (string)reader["pkid"].ToString();
Label3.Text = (string)reader["Artikal"].ToString();
Label23.Text = (string)reader["Vid"].ToString();
Label10.Text = (string)reader["EdMera"].ToString();
Label7.Text = (string)reader["TarifaID"].ToString();
Label4.Text = (string)reader["Cena1"].ToString();
decimal cena = Convert.ToDecimal(Label5.Text);//kolicina
decimal kolicina = Convert.ToDecimal(Label4.Text);//cena
//vkIznos
decimal mnoz = cena * kolicina;
Label6.Text = mnoz.ToString();
Convert.ToDecimal(Label6.Text);
conn.Close();
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
if (Label37.Text == "0")
{
dtCurrentTable.Rows[0]["Kolicina"] = Label5.Text;
}
if (Label37.Text != "0")
{
//Here this current value of Label37.text need to be incremented for one each time when button is clicked.
dtCurrentTable.Rows[0]["Kolicina"] = Convert.ToInt32(Label37.Text) + 3;
}
you need viewstate,
public int Counter
{
get
{
if (ViewState["Counter"] != null)
{
return Convert.ToInt32(ViewState["Counter"]);
}
else
return 0;
}
set { ViewState["Counter"] = value; }
}
protected void Button6_Click(object sender, EventArgs e)
{
//other codes..
Counter = Counter + 1;
if (Label37.Text != "0")
{
dtCurrentTable.Rows[0]["Kolicina"] = Convert.ToInt32(Label37.Text) + Counter;
}
}

how to do gridview sorting without data Source?

i am trying to do sorting and paging for my gridview without datasource but when i click on the header of the gridview to sort it , nothing happen but when i click for paging is working fine and there is no error. how to do about it?
this is my code:
protected void Page_Load(object sender, EventArgs e)
{
dbBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtSortTable = GridView1.DataSource as DataTable;
if (dtSortTable != null)
{
DataView dvSortedView = new DataView(dtSortTable);
dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
GridView1.DataSource = dvSortedView;
GridView1.DataBind();
}
}
private string getSortDirectionString(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
if(sortDirection== SortDirection.Ascending)
{
newSortDirection = "ASC";
}
else
{
newSortDirection = "DESC";
}
return newSortDirection;
}
private void dbBind()
{
DataSet ds;
string startdate = (string)(Session["startdate"]);
string enddate = (string)(Session["enddate"]);
var format = "dd/MM/yyyy";
DateTime one = DateTime.ParseExact(startdate, format, CultureInfo.InvariantCulture);
DateTime two = DateTime.ParseExact(enddate, format, CultureInfo.InvariantCulture);
if (two >= one)
{
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=n;Integrated Security=True");
//conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [AmountSpent], [TimeDate]=convert(nvarchar,timedate,103), [StallNo] FROM [StudentTransactions] WHERE TimeDate BETWEEN #one AND #two", conn);
cmd.Parameters.AddWithValue("#one", one);
cmd.Parameters.AddWithValue("#two", two);
ds = new DataSet();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
if (ds.Tables.Count > 0)
{
DataView dv = ds.Tables[0].DefaultView;
if (ViewState["SortDirection"] != null)
{
sortDirection = ViewState["SortDirection"].ToString();
}
if (ViewState["SortExpression"] != null)
{
sortExpression = ViewState["SortExpression"].ToString();
dv.Sort = string.Concat(sortExpression, " ", sortDirection);
}
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
//GridView1.DataBind();
//conn.Close();
}
else
{
GridView1.Visible = false;
string strMsg = " Data not found for the choosen dates.";
Response.Write("<script>alert('" + strMsg + "')</script>");
}
}

Gridview Sort Causing RowDataBound to not function correctly

I have a gridview that works just fine with each of my row commands, however, once it is sorted it causes the rowdatabound event to use incorrect values rather than the actual values in the row after it has been sorted. Any help would be appreciated!
Here is my code behind.
//Verify and Update Record
protected void UnverifiedSalesGV_RowCommand(object sender, GridViewCommandEventArgs e)
{
buttonCommand = e.CommandName;
MessageLBL.Text = "";
if (e.CommandName == "VerifyRecord")
{
//Get record ID
string salesID = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (productID != "38")
{
verifyRenewal = false;
try
{
UpdateSalesRecordSDS.UpdateCommand = "UPDATE Sales SET Verified = #Verified WHERE ID = #ID";
UpdateSalesRecordSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UpdateSalesRecordSDS.UpdateParameters["Verified"].DefaultValue = true.ToString();
UpdateSalesRecordSDS.Update();
UnverifiedSalesGV.DataBind();
VerifiedSalesGV.DataBind();
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not verify sale. Message: " + ex.Message;
}
}
else
{
//Get row index.
UnverifiedSalesGV.SetEditRow(Convert.ToInt32(e.CommandArgument));
verifyRenewal = true;
}
}
if (e.CommandName == "UpdateProduct")
{
DropDownList productValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("RenewalProductDDL");
if (productValue.SelectedIndex != 0)
{
try
{
UpdateSalesRecordSDS.UpdateCommand = "UPDATE Sales SET ProductID = #ProductID, Verified = #Verified WHERE ID = #ID";
UpdateSalesRecordSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UpdateSalesRecordSDS.UpdateParameters["ProductID"].DefaultValue = productValue.SelectedValue;
UpdateSalesRecordSDS.UpdateParameters["Verified"].DefaultValue = true.ToString();
UpdateSalesRecordSDS.Update();
UnverifiedSalesGV.DataBind();
UnverifiedSalesGV.EditIndex = -1;
VerifiedSalesGV.DataBind();
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not verify sale. Message: " + ex.Message;
}
}
else
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Please select renewal type.";
}
}
if (e.CommandName == "UpdateRecord")
{
//Get date and user info
DateTime getDate = System.DateTime.Now;
MembershipUser user = Membership.GetUser();
string activeuser = user.UserName;
try
{
//Get dropdown and textbox values
string commisionMonth;
string grossSalesAmount;
string netSalesAmount;
string notes;
TextBox grossSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("GrossSalesTXT");
TextBox netSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("NetSalesTXT");
TextBox notesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("NotesTXT");
DropDownList commissionMonthValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("CommissionMonthDDL");
grossSalesAmount = grossSalesValue.Text;
netSalesAmount = netSalesValue.Text;
commisionMonth = commissionMonthValue.SelectedValue;
notes = notesValue.Text;
UnverifiedSalesSDS.UpdateCommand = "UPDATE [Sales] SET [GrossSalesAmount] = #GrossSalesAmount, [NetSalesAmount] = #NetSalesAmount, [Notes] = #Notes, [CommissionMonth] = #CommissionMonth, [DateLastModified] = #DateLastModified, [UserLastModified] = #UserLastModified WHERE [ID] = #ID";
UnverifiedSalesSDS.UpdateParameters["GrossSalesAmount"].DefaultValue = grossSalesAmount;
UnverifiedSalesSDS.UpdateParameters["NetSalesAmount"].DefaultValue = netSalesAmount;
UnverifiedSalesSDS.UpdateParameters["CommissionMonth"].DefaultValue = commisionMonth;
UnverifiedSalesSDS.UpdateParameters["Notes"].DefaultValue = notes;
UnverifiedSalesSDS.UpdateParameters["DateLastModified"].DefaultValue = getDate.ToString();
UnverifiedSalesSDS.UpdateParameters["UserLastModified"].DefaultValue = activeuser;
UnverifiedSalesSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UnverifiedSalesSDS.Update();
UnverifiedSalesGV.DataBind();
UnverifiedSalesGV.EditIndex = -1;
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not update record. Message: " + ex.Message;
}
}
}
//Get product
protected void UnverifiedSalesGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
if (buttonCommand == "VerifyRecord")
{
//Get record ID
string salesID = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.Row.DataItemIndex)].Value.ToString();
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (productID == "38")
{
//Items to Hide/Display
Button UpdateProductBTN = (Button)e.Row.FindControl("UpdateProductBTN");
Button UpdateBTN = (Button)e.Row.FindControl("UpdateBTN");
Label productLBL = (Label)e.Row.FindControl("CurrentProductLBL");
DropDownList productDDL = (DropDownList)e.Row.FindControl("RenewalProductDDL");
Label grossSalesLBL = (Label)e.Row.FindControl("GrossSalesLBL");
TextBox grossSalesTXT = (TextBox)e.Row.FindControl("GrossSalesTXT");
Label netSalesLBL = (Label)e.Row.FindControl("NetSalesLBL");
TextBox netSalesTXT = (TextBox)e.Row.FindControl("NetSalesTXT");
Label commissionMonthLBL = (Label)e.Row.FindControl("SalesCommissionLBL");
DropDownList commissionMonthDDL = (DropDownList)e.Row.FindControl("CommissionMonthDDL");
TextBox notesTXT = (TextBox)e.Row.FindControl("NotesTXT");
UpdateProductBTN.Visible = true;
UpdateBTN.Visible = false;
productLBL.Visible = false;
productDDL.Visible = true;
grossSalesLBL.Visible = true;
grossSalesTXT.Visible = false;
netSalesLBL.Visible = true;
netSalesTXT.Visible = false;
commissionMonthLBL.Visible = true;
commissionMonthDDL.Visible = false;
notesTXT.Visible = false;
}
}
}
}
I was finally able to solve my problem by hardcoding in the following:
//Hide and show fields
protected void UnverifiedSalesGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == rowIndex)
{
string state = e.Row.RowState.ToString();
if (state == "Alternate, Edit" || state == "Edit")
{
//Get record ID
string salesID = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.Row.DataItemIndex)].Value.ToString();
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (productID == "38")
{
//Items to Hide/Display
Button UpdateProductBTN = (Button)e.Row.FindControl("UpdateProductBTN");
Button UpdateBTN = (Button)e.Row.FindControl("UpdateBTN");
Label productLBL = (Label)e.Row.FindControl("CurrentProductLBL");
Label accountManagerLBL = (Label)e.Row.FindControl("AccountManagerLBL");
DropDownList productDDL = (DropDownList)e.Row.FindControl("RenewalProductDDL");
DropDownList accountManagerDDL = (DropDownList)e.Row.FindControl("AccountManagerDDL");
Label grossSalesLBL = (Label)e.Row.FindControl("GrossSalesLBL");
TextBox grossSalesTXT = (TextBox)e.Row.FindControl("GrossSalesTXT");
Label netSalesLBL = (Label)e.Row.FindControl("NetSalesLBL");
TextBox netSalesTXT = (TextBox)e.Row.FindControl("NetSalesTXT");
Label commissionMonthLBL = (Label)e.Row.FindControl("SalesCommissionLBL");
DropDownList commissionMonthDDL = (DropDownList)e.Row.FindControl("CommissionMonthDDL");
TextBox notesTXT = (TextBox)e.Row.FindControl("NotesTXT");
Label notesLBL = (Label)e.Row.FindControl("NotesLBL");
UpdateProductBTN.Visible = true;
UpdateBTN.Visible = false;
productLBL.Visible = false;
productDDL.Visible = true;
accountManagerLBL.Visible = true;
accountManagerDDL.Visible = false;
grossSalesLBL.Visible = true;
grossSalesTXT.Visible = false;
netSalesLBL.Visible = true;
netSalesTXT.Visible = false;
commissionMonthLBL.Visible = true;
commissionMonthDDL.Visible = false;
notesTXT.Visible = false;
notesLBL.Visible = true;
}
}
}
}

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

Resources