Get variable from one method and use as a private string - asp.net

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

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

Grid view event not getting triggered

I have a gridview created dynamically , now i am trying to do edit each column by keeping a link button. But the rowdatabound event is not getting triggered.Where i might have gone wrong?
Below is my code :
dtValues = gObj.GetAllDocumentsHistoryList();
dtHeader = gObj.GetAllHeaderList();
GridView gvEmployee = new GridView();
gvEmployee.ShowHeaderWhenEmpty = true;
gvEmployee.EmptyDataText = "Sorry No History Records Found !!!!!!!";
gvEmployee.AutoGenerateColumns = false;
for (int i = 0; i < dtValues.Columns.Count; i++)
{
string name = dtValues.Columns[i].ColumnName.ToString();
BoundField boundfield = new BoundField();
boundfield.DataField = dtValues.Columns[i].ColumnName.ToString();
for (int j = 0; j < dtHeader.Rows.Count; j++)
{
if (dtHeader.Rows[j]["ColCode"].ToString() == dtValues.Columns[i].ColumnName.ToString())
{
boundfield.HeaderText = dtHeader.Rows[j]["ColName"].ToString();
if (boundfield.HeaderText.Contains("Date") || boundfield.HeaderText.Contains("DocExpiry"))
{
boundfield.DataFormatString = "{0:dd/MMM/yyyy}";
}
}
else if (dtValues.Columns[i].ColumnName.ToString() == "Last Modified Date")
{
boundfield.HeaderText = "Last Modified Date";
boundfield.DataFormatString = "{0:dd/MMM/yyyy}";
}
}
gvEmployee.Columns.Add(boundfield);
}
gvEmployee.DataSource = dtValues;
gvEmployee.DataBind();
gvEmployee.Width = new Unit("90%");
gvEmployee.RowDataBound += new GridViewRowEventHandler(gvEmployee_RowDataBound);
protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton lnkView = new LinkButton();
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
e.Row.Cells[3].Controls.Add(lnkView);
}
Just add your RowDataBound handler before DataBind.
Corrected Code:
gvEmployee.DataSource = dtValues;
gvEmployee.RowDataBound += new GridViewRowEventHandler(gvEmployee_RowDataBound);
gvEmployee.DataBind();
gvEmployee.Width = new Unit("90%");

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

Editing PresentationML using openxml

Hello everyone i am working on a project in which i have to export some data into a ppt using openxml on button click.Here is my code for the aspx page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DocumentFormat.OpenXml.Presentation;
using ODrawing = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
using DocumentFormat.Extensions1;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
namespace TableInPPT
{
public partial class _Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string templateFile = Server.MapPath("~/Template/Sample.potm");
string presentationFile = Server.MapPath("~/Template/SmapleNew.pptx");
PotxToPptx(templateFile, presentationFile);
//using (PresentationDocument themeDocument = PresentationDocument.Open(templateFile, false))
using (PresentationDocument prstDoc = PresentationDocument.Open(presentationFile, true))
{
AddImage(prstDoc);
AddTable(prstDoc);
}
string itemname = "SmapleNew.pptx";
Response.Clear();
Response.ContentType = "pptx";
Response.AddHeader("Content-Disposition", "attachment; filename=" + itemname + "");
Response.BinaryWrite(System.IO.File.ReadAllBytes(presentationFile));
Response.Flush();
Response.End();
}
private void PotxToPptx(string templateFile, string presentationFile)
{
MemoryStream presentationStream = null;
using (Stream tplStream = File.Open(templateFile, FileMode.Open, FileAccess.Read))
{
presentationStream = new MemoryStream((int)tplStream.Length);
tplStream.Copy(presentationStream);
presentationStream.Position = 0L;
}
using (PresentationDocument pptPackage = PresentationDocument.Open(presentationStream, true))
{
pptPackage.ChangeDocumentType(DocumentFormat.OpenXml.PresentationDocumentType.Presentation);
PresentationPart presPart = pptPackage.PresentationPart;
presPart.PresentationPropertiesPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
new Uri(templateFile, UriKind.RelativeOrAbsolute));
presPart.Presentation.Save();
}
File.WriteAllBytes(presentationFile, presentationStream.ToArray());
}
private void AddTable(PresentationDocument prstDoc)
{
// Add one slide
Slide slide = prstDoc.PresentationPart.InsertSlide1("Custom Layout", 2);
Shape tableShape = slide.CommonSlideData.ShapeTree.ChildElements.OfType<Shape>()
.Where(sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Title.Value == "TableHolder").SingleOrDefault();
if (tableShape == null) return;
// Create Graphic Frame
OpenXmlCompositeElement gElement = GetGraphicFrame(tableShape);
// Create a (6x3)Table
ODrawing.Table openXmlTable = GetSmapleTable();
// add table to graphic element
gElement.GetFirstChild<ODrawing.Graphic>().GetFirstChild<ODrawing.GraphicData>().Append(openXmlTable);
slide.CommonSlideData.ShapeTree.Append(gElement);
slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(tableShape);
prstDoc.PresentationPart.Presentation.Save();
}
private void AddImage(PresentationDocument prstDoc)
{
string imgpath = Server.MapPath("~/Template/xxxx.jpg");
Slide slide = prstDoc.PresentationPart.InsertSlide("Title and Content", 2);
Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
titleShape.NonVisualShapeProperties = new NonVisualShapeProperties
(new NonVisualDrawingProperties() { Id = 2, Name = "Title" },
new NonVisualShapeDrawingProperties(new ODrawing.ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title }));
titleShape.ShapeProperties = new ShapeProperties();
// Specify the text of the title shape.
titleShape.TextBody = new TextBody(new ODrawing.BodyProperties(),
new ODrawing.ListStyle(),
new ODrawing.Paragraph(new ODrawing.Run(new ODrawing.Text() { Text = "Trade Promotion Graph " })));
Shape shape = slide.CommonSlideData.ShapeTree.Elements<Shape>().FirstOrDefault(
sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value.ToLower().Equals("Content Placeholder 2".ToLower()));
Picture pic = slide.AddPicture(shape, imgpath);
slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(shape);
slide.Save();
prstDoc.PresentationPart.Presentation.Save();
}
private ODrawing.Table GetSmapleTable()
{
ODrawing.Table table = new ODrawing.Table();
ODrawing.TableProperties tableProperties = new ODrawing.TableProperties();
ODrawing.TableStyleId tableStyleId = new ODrawing.TableStyleId();
tableStyleId.Text = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}";
//tableStyleId.Text = "{D27102A9-8310-4765-A935-A1911B00CA55}";
tableProperties.Append(tableStyleId);
ODrawing.TableGrid tableGrid = new ODrawing.TableGrid();
ODrawing.GridColumn gridColumn1 = new ODrawing.GridColumn() { Width = 2600000L};
ODrawing.GridColumn gridColumn2 = new ODrawing.GridColumn() { Width = 2600000L };
//ODrawing.GridColumn gridColumn3 = new ODrawing.GridColumn() { Width = 1071600L };
//ODrawing.GridColumn gridColumn4 = new ODrawing.GridColumn() { Width = 1571600L };
//ODrawing.GridColumn gridColumn5 = new ODrawing.GridColumn() { Width = 771600L };
//ODrawing.GridColumn gridColumn6 = new ODrawing.GridColumn() { Width = 1071600L };
tableGrid.Append(gridColumn1);
tableGrid.Append(gridColumn2);
//tableGrid.Append(gridColumn3);
//tableGrid.Append(gridColumn4);
//tableGrid.Append(gridColumn5);
//tableGrid.Append(gridColumn6);
table.Append(tableProperties);
table.Append(tableGrid);
for (int row = 1; row <= 5; row++)
{
string text1 = "PARAMETERS";
string text2="VALUES";
if (row == 2)
{
text1 =Label1.Text ;
text2 = TextBox1.Text;
}
if (row == 3)
{
text1 = Label2.Text;
text2 = TextBox2.Text;
}
if (row == 4)
{
text1 = Label3.Text;
text2 = TextBox3.Text;
}
if (row == 5)
{
text1 = Label4.Text;
text2 = TextBox4.Text;
}
ODrawing.TableRow tableRow = new ODrawing.TableRow() { Height = 370840L };
tableRow.Append(new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.RunProperties() {Language = "en-US", Dirty = false, SmartTagClean = false , FontSize = 3000},
new ODrawing.Text(text1)))),
new ODrawing.TableCellProperties()));
tableRow.Append(new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.RunProperties() {Language = "en-US", Dirty = false, SmartTagClean = false , FontSize = 3000 },
new ODrawing.Text(text2)))),
new ODrawing.TableCellProperties()));
ODrawing.SolidFill solidFill = new ODrawing.SolidFill();
ODrawing.SchemeColor schemeColor = new ODrawing.SchemeColor() { Val = ODrawing.SchemeColorValues.Accent6 };
ODrawing.LuminanceModulation luminanceModulation = new ODrawing.LuminanceModulation() { Val = 75000 };
schemeColor.Append(luminanceModulation);
solidFill.Append(schemeColor);
table.Append(tableRow);
}
//for (int row = 1; row <= 3; row++)
//{
// ODrawing.TableRow tableRow = new ODrawing.TableRow() { Height = 370840L };
// for (int column = 1; column <= 6; column++)
// {
// ODrawing.TableCell tableCell = new ODrawing.TableCell();
// TextBody textBody = new TextBody() { BodyProperties = new ODrawing.BodyProperties(), ListStyle = new ODrawing.ListStyle() };
// ODrawing.Paragraph paragraph = new ODrawing.Paragraph();
// ODrawing.Run run = new ODrawing.Run();
// ODrawing.RunProperties runProperties = new ODrawing.RunProperties() { Language = "en-US", Dirty = false, SmartTagClean = false };
// ODrawing.Text text = new ODrawing.Text();
// text.Text = "Smaple Text";
// run.Append(runProperties);
// run.Append(text);
// ODrawing.EndParagraphRunProperties endParagraphRunProperties = new ODrawing.EndParagraphRunProperties() { Language = "en-US", Dirty = false };
// paragraph.Append(run);
// paragraph.Append(endParagraphRunProperties);
// textBody.Append(paragraph);
// ODrawing.TableCellProperties tableCellProperties = new ODrawing.TableCellProperties();
// ODrawing.SolidFill solidFill = new ODrawing.SolidFill();
// ODrawing.SchemeColor schemeColor = new ODrawing.SchemeColor() { Val = ODrawing.SchemeColorValues.Accent6 };
// ODrawing.LuminanceModulation luminanceModulation = new ODrawing.LuminanceModulation() { Val = 75000 };
// schemeColor.Append(luminanceModulation);
// solidFill.Append(schemeColor);
// tableCellProperties.Append(solidFill);
// tableCell.Append(textBody);
// tableCell.Append(tableCellProperties);
// tableRow.Append(tableCell);
// if (column == 1 && row == 1)
// {
// tableRow.Append(CreateTextCell("category"));
// }
// }
// }
return table;
}
static ODrawing.TableCell CreateTextCell(string text)
{
ODrawing.TableCell tc = new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.Text(text)))),
new ODrawing.TableCellProperties());
return tc;
}
private static OpenXmlCompositeElement GetGraphicFrame(Shape refShape)
{
GraphicFrame graphicFrame = new GraphicFrame();
int contentPlaceholderCount = 0;
UInt32Value graphicFrameId = 1000;
NonVisualGraphicFrameProperties nonVisualGraphicFrameProperties = new NonVisualGraphicFrameProperties();
NonVisualDrawingProperties nonVisualDrawingProperties = new NonVisualDrawingProperties()
{
Id = ++graphicFrameId,
Name = "Table" + contentPlaceholderCount.ToString(),
};
NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties = new NonVisualGraphicFrameDrawingProperties();
ODrawing.GraphicFrameLocks graphicFrameLocks = new ODrawing.GraphicFrameLocks() { NoGrouping = true };
nonVisualGraphicFrameDrawingProperties.Append(graphicFrameLocks);
ApplicationNonVisualDrawingProperties applicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
PlaceholderShape placeholderShape = new PlaceholderShape() { Index = graphicFrameId };
applicationNonVisualDrawingProperties.Append(placeholderShape);
nonVisualGraphicFrameProperties.Append(nonVisualDrawingProperties);
nonVisualGraphicFrameProperties.Append(nonVisualGraphicFrameDrawingProperties);
nonVisualGraphicFrameProperties.Append(applicationNonVisualDrawingProperties);
Transform transform = new Transform()
{
Offset = new ODrawing.Offset() { X = refShape.ShapeProperties.Transform2D.Offset.X, Y = refShape.ShapeProperties.Transform2D.Offset.Y },
Extents = new ODrawing.Extents() { Cx = refShape.ShapeProperties.Transform2D.Extents.Cx, Cy = refShape.ShapeProperties.Transform2D.Extents.Cy }
};
ODrawing.Graphic graphic = new ODrawing.Graphic();
ODrawing.GraphicData graphicData = new ODrawing.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/table" };
graphic.Append(graphicData);
graphicFrame.Append(nonVisualGraphicFrameProperties);
graphicFrame.Append(transform);
graphicFrame.Append(graphic);
return graphicFrame;
}
}
}
Please note that the template used is a sample template containing two slides only i.e. one title slide and one more blank side with a wordart having some random text written on it.
Also the table is filled with data from 4 textboxes present on the aspx page.
And here is the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using DocumentFormat.OpenXml.Presentation;
using ODrawing = DocumentFormat.OpenXml.Drawing;
using Drawing = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
namespace DocumentFormat.Extensions1
{
public static class Extensions1
{
internal static Slide InsertSlide(this PresentationPart presentationPart, string layoutName, int absolutePosition)
{
int slideInsertedPostion = 0;
UInt32 slideId = 256U;
slideId += Convert.ToUInt32(presentationPart.Presentation.SlideIdList.Count());
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = presentationPart.AddNewPart<SlidePart>();
slide.Save(sPart);
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(sPart);
slideInsertedPostion = presentationPart.SlideParts.Count();
presentationPart.Presentation.Save();
var returnVal = ReorderSlides(presentationPart, slideInsertedPostion - 1, absolutePosition - 1);
return GetSlideByRelationshipId(presentationPart, newSlideId.RelationshipId);
}
public static Slide InsertSlide1(this PresentationPart presentationPart, string layoutName, int absolutePosition)
{
int slideInsertedPostion = 0;
UInt32 slideId = 256U;
slideId += Convert.ToUInt32(presentationPart.Presentation.SlideIdList.Count());
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = presentationPart.AddNewPart<SlidePart>();
slide.Save(sPart);
SlideMasterPart smPart = presentationPart.SlideMasterParts.First();
SlideLayoutPart slPart = smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName));
//SlideLayoutPart slPart = smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName));
sPart.AddPart<SlideLayoutPart>(slPart);
sPart.Slide.CommonSlideData = (CommonSlideData)smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName)).SlideLayout.CommonSlideData.Clone();
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(sPart);
slideInsertedPostion = presentationPart.SlideParts.Count();
presentationPart.Presentation.Save();
var returnVal = ReorderSlides(presentationPart, slideInsertedPostion - 1, absolutePosition - 1);
return GetSlideByRelationshipId(presentationPart, newSlideId.RelationshipId);
}
internal static int ReorderSlides(PresentationPart presentationPart, int currentSlidePosition, int newPosition)
{
int returnValue = -1;
if (newPosition == currentSlidePosition) { return returnValue; }
int slideCount = presentationPart.SlideParts.Count();
if (slideCount == 0) { return returnValue; }
int maxPosition = slideCount - 1;
CalculatePositions(ref currentSlidePosition, ref newPosition, maxPosition);
if (newPosition != currentSlidePosition)
{
DocumentFormat.OpenXml.Presentation.Presentation presentation = presentationPart.Presentation;
SlideIdList slideIdList = presentation.SlideIdList;
SlideId sourceSlide = (SlideId)(slideIdList.ChildElements[currentSlidePosition]);
SlideId targetSlide = (SlideId)(slideIdList.ChildElements[newPosition]);
sourceSlide.Remove();
if (newPosition > currentSlidePosition)
{
slideIdList.InsertAfter(sourceSlide, targetSlide);
}
else
{
slideIdList.InsertBefore(sourceSlide, targetSlide);
}
returnValue = newPosition;
}
presentationPart.Presentation.Save();
return returnValue;
}
private static void CalculatePositions(ref int originalPosition, ref int newPosition, int maxPosition)
{
if (originalPosition < 0)
{
originalPosition = maxPosition;
}
if (newPosition < 0)
{
newPosition = maxPosition;
}
if (originalPosition > maxPosition)
{
originalPosition = maxPosition;
}
if (newPosition > maxPosition)
{
newPosition = maxPosition;
}
}
private static Slide GetSlideByRelationshipId(PresentationPart presentationPart, DocumentFormat.OpenXml.StringValue relId)
{
SlidePart slidePart = presentationPart.GetPartById(relId) as SlidePart;
if (slidePart != null)
{
return slidePart.Slide;
}
else
{
return null;
}
}
internal static Picture AddPicture(this Slide slide, Shape referingShape, string imageFile)
{
Picture picture = new Picture();
string embedId = string.Empty;
UInt32Value picId = 10001U;
string name = string.Empty;
if (slide.Elements<Picture>().Count() > 0)
{
picId = ++slide.Elements<Picture>().ToList().Last().NonVisualPictureProperties.NonVisualDrawingProperties.Id;
}
name = "image" + picId.ToString();
embedId = "rId" + (slide.Elements<Picture>().Count() + 915).ToString(); // some value
NonVisualPictureProperties nonVisualPictureProperties = new NonVisualPictureProperties()
{
NonVisualDrawingProperties = new NonVisualDrawingProperties() { Name = name, Id = picId, Title = name },
NonVisualPictureDrawingProperties = new NonVisualPictureDrawingProperties() { PictureLocks = new Drawing.PictureLocks() { NoChangeAspect = true } },
ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties() { UserDrawn = true }
};
BlipFill blipFill = new BlipFill() { Blip = new Drawing.Blip() { Embed = embedId } };
Drawing.Stretch stretch = new Drawing.Stretch() { FillRectangle = new Drawing.FillRectangle() };
blipFill.Append(stretch);
ShapeProperties shapeProperties = new ShapeProperties()
{
Transform2D = new Drawing.Transform2D()
{
Offset = new Drawing.Offset() { X = 1554691, Y = 1600200 },
Extents = new Drawing.Extents() { Cx = 6034617, Cy = 4525963 }
}
};
Drawing.PresetGeometry presetGeometry = new Drawing.PresetGeometry() { Preset = Drawing.ShapeTypeValues.Rectangle };
Drawing.AdjustValueList adjustValueList = new Drawing.AdjustValueList();
presetGeometry.Append(adjustValueList);
shapeProperties.Append(presetGeometry);
picture.Append(nonVisualPictureProperties);
picture.Append(blipFill);
picture.Append(shapeProperties);
slide.CommonSlideData.ShapeTree.Append(picture);
// Add Image part
slide.AddImagePart(embedId, imageFile);
slide.Save();
return picture;
}
private static void AddImagePart(this Slide slide, string relationshipId, string imageFile)
{
ImagePart imgPart = slide.SlidePart.AddImagePart(GetImagePartType(imageFile), relationshipId);
using (FileStream imgStream = File.Open(imageFile, FileMode.Open))
{
imgPart.FeedData(imgStream);
}
}
private static ImagePartType GetImagePartType(string imageFile)
{
string[] imgFileSplit = imageFile.Split('.');
string imgExtension = imgFileSplit.ElementAt(imgFileSplit.Count() - 1).ToString().ToLower();
if (imgExtension.Equals("jpg"))
imgExtension = "jpeg";
return (ImagePartType)Enum.Parse(typeof(ImagePartType), imgExtension, true);
}
public static void Copy(this Stream source, Stream target)
{
if (source != null)
{
MemoryStream mstream = source as MemoryStream;
if (mstream != null) mstream.WriteTo(target);
else
{
byte[] buffer = new byte[2048];
int length = buffer.Length, size;
while ((size = source.Read(buffer, 0, length)) != 0)
target.Write(buffer, 0, size);
}
}
}
}
}
Now here are my queries:
1.In the aspx page if i try to replace the templateFile with my own template(same as the sample)it gives me an error "Object reference not set to an instance of an object" at this line Where(sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Title.Value == "TableHolder") under AddTable.Otherwise it works fine.
2.Also in the second slide i am getting the required table but with the word "image" written 5 times on top of the page.
3.Also in the powerpoint file generated,the template style is not displayed on the slides except the first and the last slide(i.e the slides which are there in the template).
Thank you.

Resources