I'm attempting to use the code below to fill a PDF template with data from my webform. I want to know if it is possible to put a gridview into the form. Researching gives me mixed responses with some saying it can't be done and others that it can. I am not an experienced developer. Thanks in advance!
protected void btnPrint_Click(object sender, EventArgs e)
{
PdfPTable pdfTable = new PdfPTable(GridView2.HeaderRow.Cells.Count);
foreach (TableCell headerCell in GridView2.HeaderRow.Cells)
{
Font font = new Font();
font.Color = new BaseColor(GridView2.HeaderStyle.ForeColor);
PdfPCell pdfCell = new PdfPCell(new Phrase(headerCell.Text, font));
pdfCell.BackgroundColor = new BaseColor(GridView2.HeaderStyle.BackColor);
pdfTable.AddCell(pdfCell);
}
foreach (GridViewRow gridViewRow in GridView2.Rows)
{
foreach (TableCell tableCell in gridViewRow.Cells)
{
Font font = new Font();
font.Color = new BaseColor(GridView2.RowStyle.ForeColor);
PdfPCell pdfCell = new PdfPCell(new Phrase(tableCell.Text));
pdfCell.BackgroundColor = new BaseColor(GridView2.RowStyle.BackColor);
pdfTable.AddCell(pdfCell);
}
}
string fileNameExisting = Server.MapPath("~/Invoices/Invoice_Template.pdf");
string fileNameNew = Server.MapPath("~/Invoices/" + GridView1.SelectedRow.Cells[2].Text + "_Invoice.pdf");
PdfReader pdfReader = new PdfReader(fileNameExisting);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(fileNameNew, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.SetField("txtName", txtEmail.Text);
**pdfFormFields.SetField("table", pdfTable);**
string sTmp = "Invoice Generated for " + pdfFormFields.GetField("txtName");
MessageBox.Show(sTmp, "Finished");
pdfStamper.FormFlattening = false;
pdfStamper.Close();
}
Related
I am binding a listview to datatable variable. My idea is to modify the DataTable upon Delete, Insert, Update Requests from ListView, and save it to Database only when user wants. But, after postback, my DataTable becomes null. Is there any way to resolve it? Is this right way to bind a ListView without connecting Database ?
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){
DataTable DTReceipts = new DataTable("DTReceipts");
DTReceipts.Columns.AddRange(new DataColumn[] {
new DataColumn("ExpenseReceiptID", Type.GetType("System.Int32")),
new DataColumn("TransactionSeqNumber", Type.GetType("System.Int32")),
new DataColumn("TransactionSeqSub", Type.GetType("System.String")),
new DataColumn("TransactionDate", Type.GetType("System.DateTime")),
new DataColumn("ReceiptNumber", Type.GetType("System.String")),
new DataColumn("Vendor_EntityID", Type.GetType("System.Int32")),
new DataColumn("Description", Type.GetType("System.String")),
new DataColumn("SubProjectID", Type.GetType("System.Int32")),
new DataColumn("AllocationID", Type.GetType("System.Int32")),
new DataColumn("AllocationScope", Type.GetType("System.String")),
new DataColumn("DeductFromVendor_EntityID", Type.GetType("System.Int32")),
new DataColumn("DeductionAmount", Type.GetType("System.Double")),
new DataColumn("EmployeeID", Type.GetType("System.Int32"))
});
for (int i = 1; i <= 20; i++)
{
DataRow drr = DTReceipts.NewRow();
drr["ExpenseReceiptID"] = DBNull.Value;
drr["TransactionSeqNumber"] = i.ToString();
drr["TransactionSeqSub"] = "";
drr["TransactionDate"] = DBNull.Value;
drr["ReceiptNumber"] = DBNull.Value;
drr["Vendor_EntityID"] = DBNull.Value;
drr["Description"] = DBNull.Value;
drr["SubProjectID"] = DBNull.Value;
drr["AllocationID"] = DBNull.Value;
drr["AllocationScope"] = DBNull.Value;
drr["DeductFromVendor_EntityID"] = DBNull.Value;
drr["DeductionAmount"] = DBNull.Value;
drr["EmployeeID"] = DBNull.Value;
DTReceipts.Rows.Add(drr);
}
ExpenseReceiptsList.DataSource = DTReceipts;
ExpenseReceiptsList.DataBind();
}
}
Basically I create Rows then Cells then i populate the Cells with LinkButton which is getting Text value from XML nodes .
Code :
private void linkBTN_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
string text = btn.Text.ToString();
XmlDocument clickDoc = new XmlDocument();
clickDoc.Load(Server.MapPath("~/ProductShow.xml"));
XmlNodeList btnNode = clickDoc.SelectNodes("products/" + text.ToString() + "/*");
int count = btnNode.Count;
foreach (XmlNode node in btnNode)
{
TableRow row = new TableRow();
TableCell cell = new TableCell();
cell.CssClass = "Cell";
LinkButton linkbtn = new LinkButton();
linkbtn.Text = node.InnerText;
linkbtn.Attributes.Add("runat", "server");
Image img = new Image();
cell.Controls.Add(linkbtn);
cell.Controls.Add(new LiteralControl("<br/>"));
cell.Controls.Add(img);
row.Cells.Add(cell);
MainTable.Rows.Add(row);
}
}
My problem is that i want to create 4 cells for each row and my code creates 1 cell for each row untill the Nodes end
You need another loop to add more columns to each row
foreach (XmlNode node in btnNode)
{
TableRow row = new TableRow();
for (int i = 0; i < 4; i++){
TableCell cell = new TableCell();
cell.CssClass = "Cell";
LinkButton linkbtn = new LinkButton();
linkbtn.Text = node.InnerText;
linkbtn.Attributes.Add("runat", "server");
Image img = new Image();
cell.Controls.Add(linkbtn);
cell.Controls.Add(new LiteralControl("<br/>"));
cell.Controls.Add(img);
row.Cells.Add(cell);
}
MainTable.Rows.Add(row);
}
I am trying to add values in table rows on button click. It's working on database but not working on web page. It override on last row on page.
How can I generate new row on every button click.
here is my button click code--
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//Label2.Visible = false;
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
CheckBox cb1 = new CheckBox();
I = Hidden1.Value;
I += 1;
cb1.ID = "cb1" + I;
TableRow Table1Row = new TableRow();
Table1Row.ID = "Table1Row" + I;
TableCell RCell1 = new TableCell();
RCell1.Controls.Add(cb1);
TableCell RCell2 = new TableCell();
RCell2.Text = txtName.Text;
tblLanguagesRow.Cells.Add(RCell1);
tblLanguagesRow.Cells.Add(RCell2);
tblLanguages.Rows.Add(tblLanguagesRow);
Hidden1.Value = I;
btnAdd.Visible = true;
btnDelete.Visible = true;
Label2.Visible = true;
Label2.Text = "Successfully Added";
add();
}
txtName.Text = "";
}
public int add()
{
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("hrm_AddLanguages", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtName.Text;
command.Parameters.Add("#CreatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#UpdatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#CreatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#UpdatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#IsDeleted", SqlDbType.Bit).Value = 0;
sqlConnection.Open();
return command.ExecuteNonQuery();
}
Please Help me.
If possible try to do this using Grid view. It is better to use grid view instead of table.
Check out below link. It will help you to find your solution.
DataTable in ASP.Net Session
I'm having trouble getting the DataSet into a webform textbox with the name PrefixDescription. I tried to convert the row into a string, and I then tried to put the string into the textbox. However, nothing appears in the textbox. The DataSet does have data. I tried databinding and databind, but those don't work either.
private DirectoryEntry testAD = new DirectoryEntry();
private DataTable DT = new DataTable();
protected void Button2_Click(object sender, EventArgs e)
{
DirectorySearcher search = new DirectorySearcher(testAD);
SearchResultCollection myResults = search.FindAll();
search.PropertiesToLoad.Add("name");
DT.Columns.Add("name");
DT.Columns.Add();
foreach (SearchResult SR in myResults)
{
DataRow dr = DT.NewRow();
DirectoryEntry DE = SR.GetDirectoryEntry();
dr["name"] = DE.Properties["name"].Value;
DT.Rows.Add(dr);
DT.AcceptChanges();
PrefixDescription.Text = Convert.ToString(dr["name"]);
DE.Close();
}
}
Better yet, use a StringBuilder, something like this..
System.Text.StringBuilder builder = new System.Text.StringBuilder();
foreach (SearchResult SR in myResults)
{
DataRow dr = DT.NewRow();
DirectoryEntry DE = SR.GetDirectoryEntry();
dr["name"] = DE.Properties["name"].Value;
DT.Rows.Add(dr);
DT.AcceptChanges();
builder.Append(Convert.ToString(dr["name"]));
PrefixDescription.Text = Convert.ToString(dr["name"]);
DE.Close();
}
PrefixDescription.Text = builder.ToString();
I am exporting gridview data to excel but that excel file add the some lable text and textbox values and format also taken , pls give how to design the excel code in asp.net. I am writing like this
All gridview data taken dataset ds
-pls give me textbox values and some label or normal text designed code in excel
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = ds;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=DataTable.xls");
Response.Charset = string.Empty;
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
////Apply text style to each Row
GridView1.Rows[i].Cells[4].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:'\#,\#\#0\.00';}
.textmode1(mso-number-format:'\#';}
.SSNmode{mso-number-format:'000-00-000';} </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
Take a look at this awesome tool: http://www.carlosag.net/Tools/ExcelXmlWriter/
Futhermore, the author also created a code generator, which generates .net code from a provided excel sheet(formatting, layout and so on)
http://www.carlosag.net/Tools/ExcelXmlWriter/Generator.aspx
Here's some code that generates an excel file from a datatable (converted vb code, as pr. request by poster)
CarlosAg.ExcelXmlWriter.Workbook book = new CarlosAg.ExcelXmlWriter.Workbook();
book.ExcelWorkbook.ProtectWindows = false;
book.ExcelWorkbook.ProtectStructure = false;
var styles = book.Styles;
WorksheetStyle defaultStyle = styles.Add("Default");
var defStyles = defaultStyle;
defStyles.Name = "Normal";
defStyles.Font.FontName = "Calibri";
defStyles.Font.Size = 11;
defStyles.Font.Color = "#000000";
defStyles.Alignment.Vertical = StyleVerticalAlignment.Bottom;
Worksheet sheet = book.Worksheets.Add("Sheet1");
sheet.Table.DefaultRowHeight = 15f;
sheet.Table.FullColumns = 1;
sheet.Table.FullRows = 1;
DataTable dt = new DataTable(); //= your datatable
//Header
WorksheetRow HeaderRow = sheet.Table.Rows.Add();
foreach (DataColumn col in dt.Columns)
{
HeaderRow.Cells.Add(col.ColumnName.ToString());
}
//Body
foreach (DataRow dr in dt.Rows)
{
WorksheetRow row = sheet.Table.Rows.Add();
foreach (DataColumn cols in dt.Columns)
{
row.Cells.Add(dr[cols.ColumnName.ToString()].ToString());
}
}
sheet.Options.Selected = true;
sheet.Options.ProtectObjects = false;
sheet.Options.ProtectScenarios = false;
book.Save("path to file");