This is very close to working. Not sure why I am getting an error at document.Close() or why I am getting a corrupt pdf when I delete document.Close().
It seems to not be posting any info to the pdf.
The code:
Main page with the button the user clicks:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="EventList.ascx.cs"
Inherits="Objects_EventList" %>
<asp:ListView runat="server" ID="lstvwEvents"
OnItemDataBound="lstvwEvents_OnItemDataBound">
<LayoutTemplate>
<asp:ImageButton BorderStyle="0" CssClass="submitbutton" runat="server" AlternateText="Get PDF" ID="LinkButton1" OnClick="btnGenerateReport" />
<div class="eventtease" style="width: 249px;border-bottom: 1px solid #c0c06b;padding-right: 10px;padding-top: 10px;height: 300px;overflow: auto;">
<asp:Literal runat="server" ID="itemPlaceholder" />
<div style="clear: both;"></div>
</div>
</LayoutTemplate>
<ItemTemplate>
<h3 style="clear: both;border-top: 1px solid #c0c06b;padding-top: 10px;"><asp:Literal runat="server" ID="ltrlShortDate" /><br /><%# Eval("EventName").ToString().ToUpper() %><br />(<asp:Literal runat="server" ID="ltrlTimes" />)</h3>
<p class="eventdescription" style="font: normal normal normal 7.5pt/normal Arial, Sans-Serif;margin-top: 3px;">
<%# Eval("Description") %>
</p>
<asp:HyperLink runat="server" ID="lnkLearnMore" Text="LEARN MORE" CssClass="learnmore" Visible="false" />
</ItemTemplate>
Here is the code behind:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.IO;
public partial class Objects_EventList : System.Web.UI.UserControl
{
public string city;
public int showcount;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Load_Events();
};
}
protected void Load_Events()
{
EventsDataContext edc = new EventsDataContext();
var events = (from e in edc.tblEvents_Cafes
where e.EventDateTime >= DateTime.Now && e.VenueCity.Trim() == city.Trim() && (e.VenueName.Contains("Café") || e.VenueName.Contains("Cafe") )
orderby e.EventDateTime
select new
{
EventName = e.EventName,
EventDate = e.EventDate,
EventTime = e.EventTime,
Description = edc.tblEvents_Cafe_Descriptions.OrderBy(d => d.Priority).Where(d => d.Keywords.ToLower() == e.EventName.ToLower()).Select(d => d.Description).First(), // edc.tblEvents_Cafe_Descriptions.OrderBy(d => d.Priority).Where(d => d.Keywords.ToLower() == e.EventName.ToLower() || d.Keywords.ToLower().CompareTo(e.EventName.ToLower()) >= 0).Select(d => d.Description).First()
}).Take(showcount);
lstvwEvents.DataSource = events;
lstvwEvents.DataBind();
}
protected void lstvwEvents_OnItemDataBound(Object sender, ListViewItemEventArgs e)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
var tempevent = dataItem.DataItem;
Type t = tempevent.GetType();
DateTime tempdate;
if (DateTime.TryParse((t.GetProperty("EventDate").GetValue(tempevent, null)).ToString(), out tempdate))
{
Literal ltrlShortDate = new Literal();
ltrlShortDate = (Literal)e.Item.FindControl("ltrlShortDate");
ltrlShortDate.Text = tempdate.ToString("MM/dd/yyyy");
}
if (DateTime.TryParse((t.GetProperty("EventTime").GetValue(tempevent, null)).ToString(), out tempdate))
{
Literal ltrlTimes = new Literal();
ltrlTimes = (Literal)e.Item.FindControl("ltrlTimes");
ltrlTimes.Text = tempdate.ToString("hh:mm tt");
}
}
}
private void GeneratePDF(string path, string fileName, bool download, string text)
{
var document = new Document();
try {
if (download) {
PdfWriter.GetInstance(document, Response.OutputStream);
} else {
PdfWriter.GetInstance(document, new FileStream(path + fileName, FileMode.Create));
}
StringBuilder strB = new StringBuilder();
document.Open();
if (text.Length.Equals(0)) {
lstvwEvents.DataBind();
using (StringWriter sWriter = new StringWriter(strB)) {
using (HtmlTextWriter htWriter = new HtmlTextWriter(sWriter)) {
ListView lv1 = lstvwEvents;
lv1.RenderControl(htWriter);
}
}
} else {
strB.Append(text);
}
using (TextReader sReader = new StringReader(strB.ToString())) {
List<IElement> list = HTMLWorker.ParseToList(sReader, new StyleSheet());
foreach (IElement elm in list) {
document.Add(elm);
}
}
} catch (Exception ee) {
ee.ToString();
} finally {
document.Close();
}
}
protected void btnGenerateReport(object sender, EventArgs e)
{
string fileName = "Calendar.pdf";
GeneratePDF("", fileName, true, "");
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.Flush();
Response.End();
}
}
Related
I have 2 pages (Trial.aspx and TestCallBack.aspx). Trail.aspx will first be editable mode. Now from TestCallBack.aspx i will redirect back to Trail.aspx but all the controls should be read only format. I have given the source code details below. Only the textbox of trial.aspx is readonly, the gridview is not seen at all.
Trial.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Trial.aspx.cs" Inherits="PTest.Trial" EnableEventValidation ="true" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtVisitor" runat="server"></asp:TextBox>
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" ShowHeaderWhenEmpty ="true" Visible ="true">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Trial.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace PTest
{
public partial class Trial : System.Web.UI.Page
{
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("txtDate");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("txtDate");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string name = Request.QueryString["value"];
if (name == "true")
{
hidecontrols();
}
else
{
SetInitialRow();
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void hidecontrols()
{
foreach (Control c in Page.Controls)
{
if (c is GridView)
((GridView)(c)).Enabled = false;
foreach (Control ctrl in c.Controls)
{
if (ctrl is TextBox)
{
((TextBox)(ctrl)).Enabled = false;
}
else if (ctrl in GridView)
{
((GridView)(ctrl).Enabled =false;
}
}
}
}
}
}
TestCallBack.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestCallBack.aspx.cs" Inherits="PTest.TestCallBack" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
TestCallBack.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PTest
{
public partial class TestCallBack : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Trial.aspx?value=true");
}
}
}
After reading your comment it would appear your problem is here:
if (!Page.IsPostBack)
{
string name = Request.QueryString["value"];
if (name == "true")
{
hidecontrols();
}
else
{
SetInitialRow();
}
}
You're essentially saying If this page isn't a postback then perform this IF statement - and then in the IF statement you're saying IF there is a qstring value hide controls. Since you are redirecting back to this page it will not be a postback, and since you will have a qstring value it will hide the controls.
Perhaps try something like this:
SetInitialRow();
if (!Page.IsPostBack)
{
string name = Request.QueryString["value"];
if (name == "true")
{
GridView1.ShowFooter = false;
}
else
{
GridView1.ShowFooter = true;
}
}
Not sure if this is what you're actually after, though the problem is with your if-else in your page load. Perhaps if you update your Q with the actual flow you're after; it would help us help you more.
I have the following code for a tab container and i am able to create a tab dynamically but as soon as i try to click to add another tab the previous tab disappears, i can't figure out how to keep viewstate, can someone please help me with this.
test5.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="test5.aspx.cs" Inherits="test5" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<cc1:tabcontainer id="TabContainer1" visible="true" runat="server" Height="150px">
<cc1:TabPanel ID="Tab0" runat="server" HeaderText="Step 1">
<ContentTemplate>
Test
<asp:Button ID="add" Text="Add" OnClick="add_Click" runat="server" />
</ContentTemplate>
</cc1:TabPanel>
</cc1:tabcontainer>
</div>
</form>
</body>
</html>
test5.aspx.cs
using AjaxControlToolkit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class test5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void add_Click(object sender, EventArgs e)
{
int currentTab = TabContainer1.ActiveTabIndex;
int nextTab = currentTab + 1;
Button btn = new Button();
btn.ID = "Add" + nextTab.ToString();
btn.Text = "Add";
btn.Click += new EventHandler(add_Click);
TabPanel t = new TabPanel();
t.ID = "Tab" + nextTab;
t.HeaderText = "Tab:" + nextTab;
t.Controls.Add(btn);
TabContainer1.Tabs.Add(t);
}
}
Here's what I'd do:
Wrap the following code:
Button btn = new Button();
btn.ID = "Add" + nextTab.ToString();
btn.Text = "Add";
btn.Click += new EventHandler(add_Click);
TabPanel t = new TabPanel();
t.ID = "Tab" + nextTab;
t.HeaderText = "Tab:" + nextTab;
t.Controls.Add(btn);
TabContainer1.Tabs.Add(t);
Into its own method called RenderDynamicTabs(int nextTab)
At the end of add_Click, add this code:
if(null == ViewState["NumDynamicControls"])
{
ViewState["NumDynamicControls"] = 0;
}
var dynamicControlCount = int.Parse(ViewState["NumDynamicControls"]);
dynamicControlCount++;
In Page_Load, add the following:
if(null != ViewState["NumDynamicControls"])
{
// There are controls that need to be re-generated
var dynamicControlCount = int.Parse(ViewState["NumDynamicControls"]);
for(int i = 1; i <= dynamicControlCount; i++)
{
RenderDynamicTabs(i);
}
}
That should both store and re-render your controls after each PostBack.
Finally, to avoid duplication of code, in add_Click, replace the code you copy-pasted into RenderDynamicTabs with just a call to RenderDynamicTabs(nextTab);.
i removed the additions i added before, but here is what i got so far
using AjaxControlToolkit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class test5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (null != ViewState["NumDynamicControls"])
{
// There are controls that need to be re-generated
var dynamicControlCount = int.Parse(ViewState["NumDynamicControls"].ToString());
for (int i = 1; i <= dynamicControlCount; i++)
{
RenderDynamicTabs(i);
}
}
}
public void RenderDynamicTabs(int nextTab)
{
Button btn = new Button();
btn.ID = "Add" + nextTab.ToString();
btn.Text = "Add";
btn.Click += new EventHandler(add_Click);
TabPanel t = new TabPanel();
t.ID = "Tab" + nextTab;
t.HeaderText = "Tab:" + nextTab;
t.Controls.Add(btn);
TabContainer1.Tabs.Add(t);
}
protected void add_Click(object sender, EventArgs e)
{
int currentTab = TabContainer1.ActiveTabIndex;
int nextTab = currentTab + 1;
RenderDynamicTabs(nextTab);
if (null == ViewState["NumDynamicControls"])
{
ViewState["NumDynamicControls"] = 0;
}
var dynamicControlCount = int.Parse(ViewState["NumDynamicControls"].ToString());
dynamicControlCount = dynamicControlCount + 1;
}
}
This is my aspx page..................
<asp:Panel ID="UpdatePanel1" runat="server" Visible="false" >
<rsweb:ReportViewer ID="ReportingForPrintingReportViewer" runat="server"
Width="100%" Height="100%" Font-Names="Verdana" Font-Size="8pt"
InteractiveDeviceInfos="(Collection)" WaitMessageFont-Names="Verdana"
WaitMessageFont-Size="14pt">
<LocalReport ReportPath="Report.rdlc">
<DataSources>
<rsweb:ReportDataSource DataSourceId="ObjectDataSource2" Name="DataSet1" />
</DataSources>
</LocalReport>
</rsweb:ReportViewer>
<asp:ObjectDataSource ID="ObjectDataSource2" runat="server"
SelectMethod="GetData" TypeName="DataSet1TableAdapters.tblTotalFeeTableAdapter">
</asp:ObjectDataSource>
</asp:Panel>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="150px"
onclick="btnSubmit_Click" />
<asp:Button ID="btnReset" runat="server" Text="Reset" Width="150px" />
<asp:Button ID="btnCreateBill" runat="server" Text="CreateBill" Width="150px"
onclick="btnCreateBill_Click"/>
<asp:PopupControlExtender ID="btnCreateBill_PopupControlExtender" OffsetX="-1100" OffsetY="115"
runat="server" DynamicServicePath="" Enabled="True" ExtenderControlID=""
TargetControlID="btnCreateBill" PopupControlID="UpdatePanel1">
</asp:PopupControlExtender>
This is my cs page
protected void btnCreateBill_Click(object sender, EventArgs e)
{
DisplayReport();
UpdatePanel1.Visible = true;
}
private DataTable TotalInfoData()
{
try
{
//DataClassesDataContext db = null;
//db = new DataClassesDataContext();
//var s = from p in db.tblTotalFeess
// where p.Class == ClassDropDownList.SelectedItem.Value && p.StudentID == Convert.ToInt32(StudentNameDropDownList.SelectedValue)
// select p;
//DataTable dt = new DataTable();
//SQLHelper sqhlpr = new SQLHelper();
//sqhlpr.SqlText = "select * from tblTotalFee where Class='" + ClassDropDownList.SelectedItem.Value + "'" + "and StudentID='" + StudentNameDropDownList.SelectedValue + "'";
//DataTable dt = sqhlpr.getDataTable(false);
//return dt;
try
{
// Open Sql Connection
SqlConnection SqlCon = new SqlConnection(#"Data Source=PRATIKPC;Initial Catalog=dbbilling2.0;Integrated Security=True");
SqlCon.Open();
// Create a Command
SqlCommand SqlComm = new SqlCommand();
SqlComm.Connection = SqlCon;
SqlComm.CommandType = CommandType.Text;
SqlComm.CommandText = "select * from tblTotalFee where Class='" + ClassDropDownList.SelectedItem.Value + "'" + "and StudentID='" + StudentNameDropDownList.SelectedValue + "'";
// Create instance of Northwind DataSetXSD
DataSet1.tblTotalFeeDataTable dtbl = new DataSet1.tblTotalFeeDataTable();
// Set a Data Commands
SqlDataAdapter SqlDa = new SqlDataAdapter(SqlComm);
SqlDa.Fill(dtbl); // Fill Data in NorthwindDataSet Object.
return dtbl;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void DisplayReport()
{
try
{
// Clear the Data Source
ReportingForPrintingReportViewer.LocalReport.DataSources.Clear();
// Set a DataSource to the report
// First Parameter - Report DataSet Name
// Second Parameter - DataSource Object i.e DataTable
ReportingForPrintingReportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", TotalInfoData()));
// OR Set Report Path
ReportingForPrintingReportViewer.LocalReport.ReportPath = HttpContext.Current.Server.MapPath("~/Report.rdlc");
// Refresh and Display Report
ReportingForPrintingReportViewer.LocalReport.Refresh();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I have to click btnCreateBill twice to generate report viewer. Why? And how can I generate report viewer in a single click of a button?
Are you call your Get Data method(Your Data Source load method
) in Inside of !ispostback ?
for look this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetData()// Your Data Source load method
}
}
This is Aspx file........................
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="AccountReportParameter.aspx.cs" Inherits="TexERP.ReportSSRS.AccountReportParameter" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <asp:UpdatePanel ID="updpnlLiteral" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlAddRecord" runat="server" BackColor="White" Height="150px" Width="600px"
Visible="true">
<td align="right" colspan="4">
<asp:Button ID="btnSubmit" runat="server" Text="Show Report" OnClick="btnSubmit_Click"
ValidationGroup="FinalSave" />
<asp:Button ID="btnCancel" runat="server" Text="Reset" UseSubmitBehavior="false"
OnClick="btnCancel_Click" />
</asp:Panel>
<rsweb:ReportViewer ID="rptvwMain" runat="server" Width="907px" Height="850px" Font-Names="Verdana"
Font-Size="8pt" ProcessingMode="Remote" ShowCredentialPrompts="false" InteractiveDeviceInfos="(Collection)"
ShowZoomControl="true">
</rsweb:ReportViewer>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
This is cs file...........
using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using BusinessAccessLevel;
using BusinessAccessLevel.Masters;
using Microsoft.Reporting.WebForms;
namespace TexERP.ReportCrystal
{
public partial class AccountReportParameter : System.Web.UI.Page
{
AccountReportBAL objAccountReportBAL;
clsSession objSession;
string pstrType;
protected void Page_Load(object sender, EventArgs e)
{
objAccountReportBAL = new AccountReportBAL();
objSession = new clsSession();
pstrType = Request.QueryString["Type"];
if (Session["objSession"] != null)
{
objSession = Session["objSession"] as clsSession;
}
objAccountReportBAL = new AccountReportBAL();
if (!IsPostBack)
{
RadDtpFromDate.SelectedDate = Convert.ToDateTime(objSession.FyFromDate);
RadDtpToDate.SelectedDate = Convert.ToDateTime(objSession.FyToDate);
}
rptvwMain.LocalReport.Refresh();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string pstrType;
pstrType = Request.QueryString["Type"];
LoadReport();
}
public class CustomReportCredentials : Microsoft.Reporting.WebForms.IReportServerCredentials
{
// local variable for network credential.
private string _UserName;
private string _PassWord;
private string _DomainName;
public CustomReportCredentials(string UserName, string PassWord, string DomainName)
{
_UserName = UserName;
_PassWord = PassWord;
_DomainName = DomainName;
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get
{
return null; // not use ImpersonationUser
}
}
public System.Net.ICredentials NetworkCredentials
{
get
{
// use NetworkCredentials
return new NetworkCredential(_UserName, _PassWord, _DomainName);
}
}
public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
{
// not use FormsCredentials unless you have implements a custom autentication.
authCookie = null;
user = password = authority = null;
return false;
}
}
void LoadReport()
{
string strCompanyName = objSession.SelCompanyName;
string strHeading = "";
string strBranchName = objSession.SelBranchName;
rptvwMain.ProcessingMode = ProcessingMode.Remote;
rptvwMain.ServerReport.ReportServerCredentials = new CustomReportCredentials(AppConfig.ReportServerUserName, AppConfig.ReportServerPassword, AppConfig.ReportServerDomain);
string strReportServerUrl = AppConfig.ReportServerUrl + AppConfig.ReportServerFolder;
rptvwMain.ServerReport.ReportServerUrl = new Uri(strReportServerUrl);
List<ReportParameter> parameters = new List<ReportParameter>();
if(pstrType == "GL")
{
strHeading = "General Ledger";
rptvwMain.ServerReport.ReportPath = "/Account/AccountGeneralLedger";
}
parameters.Add(new ReportParameter("FyId", Convert.ToInt16(objSession.FyId).ToString()));
parameters.Add(new ReportParameter("AccountGroupId", cmbAccountGroup.SelectedValue));
parameters.Add(new ReportParameter("LedgerId", cmbLedgerId.SelectedValue));
parameters.Add(new ReportParameter("BranchId", Convert.ToInt64(objSession.BranchId).ToString()));
parameters.Add(new ReportParameter("StDate", Convert.ToDateTime(RadDtpFromDate.SelectedDate).ToString()));
parameters.Add(new ReportParameter("EnDate", Convert.ToDateTime(RadDtpToDate.SelectedDate).ToString()));
parameters.Add(new ReportParameter("CompanyName", strCompanyName.ToString()));
parameters.Add(new ReportParameter("BranchName", strBranchName.ToString()));
parameters.Add(new ReportParameter("Heading",strHeading.ToString()));
rptvwMain.ServerReport.SetParameters(parameters);
rptvwMain.ServerReport.SetDataSourceCredentials(new[] { new DataSourceCredentials() { Name =AppConfig.ReportServerDataSource , UserId = AppConfig.ReportServerDSUserName, Password = AppConfig.ReportServerDSPassword } });
rptvwMain.ShowZoomControl = true;
rptvwMain.ServerReport.Refresh();
}
}
}
Try this code as reference code................
When I click my Remove button it is my intent to remove the Panel, then iterate through the remaining panels and give them a new ID from scratch I.E. if I removed Panel(3) from a list of 6 Panels I would iterate through and give them all new IDs Panels 0-5.
My issue is that I keep running into an error after I delete my panel where I have duplicate ID names. For the life of me I cannot see where I am going wrong so I am reaching out hoping I am just blind or for advice.
I was setting a breakpoint at my btnDelete function and step through it but I am not seeing my logic shortcoming in why I experience an issue with multiple Panels of the same ID.
ASPX:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage/MasterPage.master" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" EnableTheming="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<link href="App_Themes/ui-lightness/jquery-ui-1.7.2.custom.css" rel="stylesheet"
type="text/css" />
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script src="Includes/JavaScript/jquery-1.7.1.js" type="text/javascript"></script>
<script src="Includes/JavaScript/jquery.ui.datepicker.js" type="text/javascript"></script>
<script src="Includes/JavaScript/jquery.ui.widget.js" type="text/javascript"></script>
<script src="Includes/JavaScript/jquery.ui.core.js" type="text/javascript"></script>
<%--Script for the Dropdown Datepicker--%>
<script type="text/javascript">
$(function () {
$("input.datepicker").datepicker({ showOn: 'button', buttonImage: 'Includes/Images/calender.gif', buttonImageOnly: false, onSelect: function () { }
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">
<h1>
Search
<asp:HyperLink ID="HyperLink1" runat="server" ImageUrl="Includes/Images/action_help.gif"
NavigateUrl="~/user_manual.pdf" Target="_blank" ToolTip="Search Help"></asp:HyperLink></h1>
<table border="0" cellpadding="6" cellspacing="0">
<tr>
<td>
<asp:Button ID="btnAdd" runat="server" Text="Add Control" onclick="btnAdd_Click" />
<asp:Button ID="btnClear" runat="server" Text="Reset" onclick="btnClear_Click" />
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
</td>
<td>
<asp:TextBox ID="txtTitle" class="searchPage" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:PlaceHolder ID="myPlaceholder" runat="server"></asp:PlaceHolder>
</td>
Code behind:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class Search : BasePage
{
List<Users> userroles = new List<Users>();
//Panel that contains all our Dynamically added user controls.
List<Panel> persistControls = new List<Panel>();
public int userid = 0;
public byte IsActive = 1;
public int error = 0;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
// Calls three functions responsible for pulling from the Database and binding the Datagrid.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetClustersFromDB(userid);
BindGrid();
BindState();
}
else
{
// Where I am recreating my controls.
DynamicQueryRecreateLogic();
}
}
protected void DynamicQueryRecreateLogic()
{
if (Session["persistControls"] != null)
{
// Local Value that contains the members of the current persistControls session, not yet pushed to the page.
persistControls = (List<Panel>)Session["persistControls"];
int count = 0;
foreach (Panel panel in persistControls)
{
//AddQuestionTypeDropDownList(count);
panel.ID = "panel" + "(" + count.ToString() + ")";
foreach (Control control in panel.Controls)
{
if (control.GetType() == typeof(DropDownList))
{
control.ID = "list" + "(" + count.ToString() + ")";
DropDownList list = (DropDownList)panel.FindControl(control.ID);
list.SelectedIndexChanged += new EventHandler(list_SelectedIndexChanged);
}
if (control.GetType() == typeof(TextBox))
{
control.ID = "txtBox" + "(" + count.ToString() + ")";
}
}
// Re-Adding our Remove Button
Button btnRemove = new Button();
btnRemove.Click += new EventHandler(btnDelete_Click);
btnRemove.Text = "Remove";
btnRemove.CommandArgument = count.ToString();
// Pushing to Placeholder
myPlaceholder.Controls.Add(panel);
myPlaceholder.Controls.Add(btnRemove);
count++;
}
}
}
private DropDownList AddQuestionTypeDropDownList()
{
DropDownList list = new DropDownList();
list.ID = "list" + "(" + persistControls.Count.ToString() + ")";
list.Items.Add(new ListItem("--Select One--", ""));
list.Items.Add(new ListItem("Title", "1"));
list.Items.Add(new ListItem("Contact", "2"));
list.Items.Add(new ListItem("Date Created", "3"));
list.SelectedIndexChanged += new EventHandler(list_SelectedIndexChanged);
list.AutoPostBack = true;
return list;
}
private TextBox AddFieldTypeTextBox(int count)
{
TextBox box = new TextBox();
box.ID = "txtBox" + "(" + count.ToString() + ")";
return box;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
try
{
Panel panelContainer = new Panel();
panelContainer.ID = "panel" + "(" + persistControls.Count.ToString() + ")";
panelContainer.Controls.Add(AddQuestionTypeDropDownList());
Button btnRemove = new Button();
btnRemove.Click += new EventHandler(btnDelete_Click);
btnRemove.Text = "Remove";
btnRemove.CommandArgument = persistControls.Count.ToString();
persistControls.Add(panelContainer);
myPlaceholder.Controls.Add(panelContainer); // Pushes the Panel to the page.
myPlaceholder.Controls.Add(btnRemove); // Pushes our Button to the page.
Session["persistControls"] = persistControls; // put it in the session
}
catch
{
throw;
}
}
protected static string DecipherCountNumber(string IDHolder)
{
int start = IDHolder.IndexOf("(");
if (start == -1)
{
return IDHolder;
}
else
{
return IDHolder.Substring(start + 1).Replace(")", string.Empty);
}
}
protected void list_SelectedIndexChanged(object sender, EventArgs e)
{
//I need to fix the dynamic Add location. I need to track some type of enumeration or attributes of the panel for recreation.
try
{
DropDownList list = (DropDownList)sender;
string IDHolder = list.ID.ToString();
int count = Convert.ToInt32(DecipherCountNumber(IDHolder));
Panel panelContainer = persistControls.Find(delegate(Panel panel) { return panel.ID == "panel" + "(" + count.ToString() + ")"; });
if (list.SelectedIndex == 1)
{
//panelContainer.Controls.Add(AddFieldTypeTextBox(count));
}
if (list.SelectedIndex == 2)
{
//panelContainer.Controls.Remove(FindControl("txtBox" + "(" + count.ToString() + ")"));
}
if (list.SelectedIndex == 3)
{
//panelContainer.Controls.Remove(FindControl("txtBox" + "(" + count.ToString() + ")"));
}
Session["persistControls"] = persistControls;
}
catch
{
throw;
}
}
protected void btnClear_Click(object sender, EventArgs e)
{
try
{
Session["persistControls"] = null;
Response.Redirect(Request.Url.ToString());
}
catch
{
throw;
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
int deleteThisOne = int.Parse(((Button)sender).CommandArgument);
persistControls.Remove(persistControls[deleteThisOne]);
Session["persistControls"] = persistControls;
Response.Redirect(Request.Url.ToString(), false);
}
catch
{
throw;
}
}
I modified my DynamicQueryControls to do the recreation OnInit rather than at PageLoad. Quite a few issues arise from creating this at the PageLoad level.
I have a image datatype which on click of a linkbutton needs to be displayed on a seperate page
aspx page
detail view:
<asp:TemplateField HeaderText="Evidence (if any)">
<ItemTemplate>
<asp:LinkButton ID="lbEvidence" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "Evidence").ToString() == String.Empty ? "None" : DataBinder.Eval(Container.DataItem, "Evidence")%>'
CommandName="Select" CommandArgument = '<%# DataBinder.Eval(Container.DataItem, "Complaint_Id") %>'> </asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
ImageHandler.ashx
<%# WebHandler Language="C#" Class="FMMadminModule.imageHandler" %>
using System;
using System.Web;
using System.Data;
using System.Web.SessionState;
namespace FMMadminModule
{
public class imageHandler : IHttpHandler, IReadOnlySessionState
{
DataTable dt;
int key;
byte[] imageOut;
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
context.Response.ContentType = "image/jpeg";
response.BufferOutput = false;
// get the key, the index into the DataTable
key = Convert.ToInt32(request.QueryString["Complaint_ID"]);
// Prepare the datatable to hold the SNo key and the jpeg image, which will be written out
dt = new DataTable();
dt = (DataTable)context.Session["dt"];
if (!dt.Rows[key]["Evidence"].Equals(null))
{
imageOut = (byte[])dt.Rows[key]["Evidence"];
response.OutputStream.Write(imageOut, 0, imageOut.Length);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
How would I display the image on a separate page?
This is how aspx.cs looks like
protected void dvResolveComplaint_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
DetailsViewRow row = dvResolveComplaint.Rows[5];
//String RowId = (e.NewSelectedIndex).ToString();
Type csType = this.GetType();
String strScript = "<script> ";
strScript += #"var newWindow = window.open('imageHandler.ashx?Complaint_ID=" + e.CommandArgument + #"', 'Evidence', ' height=450, center:yes, width=600, status=no, resizable= yes, menubar=no, toolbar=no, location=yes, scrollbars=no, status=no')";
strScript += "</script>";
ClientScript.RegisterClientScriptBlock(csType, "ViewEvidence", strScript);
dvResolveComplaint.Attributes.Add("OnClick", strScript);
}
}
this is way overcomplicated. You don't need the linkbutton at all, just write an anchor-wrapped image in your item template and call it a day, e.g.:
<img src='url_to_your_handler' alt='complaint image' />