No valid report source is available- crystal reports - asp.net

I have created a report using crystal reports. I am using visual studio 2010. The problem occurs when I try to go to another page. When I try to navigate to page 2 or last page the error No valid report source is available appears on the screen. Does anyone have any idea what I need to do? Thanks for your time

Store you report in Session and then give report source from session on page post back
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
try
{
CrystalReportViewer1.ReportSource = (ReportDocument)Session["Report"];
CrystalReportViewer1.RefreshReport();
CrystalReportViewer1.DataBind();
}
catch (Exception ex)
{
// throw;
}
}
}
protected void CrystalReportViewer1_PreRender(object sender, EventArgs e)
{
}
protected void btnPrint_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load(Server.MapPath("Reports\\BalanceReportNew\\BalanceReport.rpt"));
rptDoc.SetDataSource(ReportData());
Session["Report"] = rptDoc;
CrystalReportViewer1.ReportSource = rptDoc;
CrystalReportViewer1.RefreshReport();
CrystalReportViewer1.DataBind();
}
public DataTable ReportData()
{
string ClassName = ddlClass.SelectedValue;
string Division = ddlDivison.SelectedValue;
string Subject = ddlSubjects.SelectedValue;
DataTable ReportData = objRpt.getReportData(ClassName, Division, Subject);
return ReportData;
}

The following should solve your issue:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//whatever you do when the page is loaded for the first time
//this could even be bindReport();
}
else
{
bindReport();
}
}
public void bindReport()
{
ReportDocument rptDoc = new ReportDocument();
dsSample ds = new dsSample(); // .xsd file name
DataTable dt = new DataTable();
// Just set the name of data table
dt.TableName = "Crystal Report Example";
dt = getMostDialledNumbers(); //This function populates the DataTable
ds.Tables[0].Merge(dt, true, MissingSchemaAction.Ignore);
// Your .rpt file path will be below
rptDoc.Load(Server.MapPath("mostDialledNumbers.rpt"));
//set dataset to the report viewer.
rptDoc.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rptDoc;
CrystalReportViewer1.RefreshReport();
//in case you have an UpdatePanel in your page, it needs to be updated
UpdatePanel1.Update();
}

Try using the solution in this thread:
No Valid report source is available
From what it says, you should be able to make it work by providing ConnectionInfo and ReportSource in the code.

#Simple Solution
I have just Solved this problem using CrystalReportViewer Navigate Event
in View report Button i have saved report document in a session
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
' -- the ds is dataset variable containing data to be displayed in the report
rptDoc.SetDataSource(ds)
Session.Add("rptdoc", rptDoc)
CrystalReportViewer1.ReportSource = rptDoc
End Sub
then in Navigate event of CrystalReportViewer i set the CrystalReportViewer data source to the Session
Protected Sub j(ByVal source As Object, ByVal e As CrystalDecisions.Web.NavigateEventArgs) Handles CrystalReportViewer1.Navigate
rpt.SetDataSource(ds)
CrystalReportViewer1.ReportSource = session("rptdoc")
End Sub
So each time before you navigate to another page in the report , CrystalReportViewer data source is set to the report document saved in the session.

Thanks to #Răzvan Panda.
Full code is given here.
protected void Page_Load(object sender, EventArgs e){
CrystalDecisions.CrystalReports.Engine.ReportDocument report =
new CrystalDecisions.CrystalReports.Engine.ReportDocument();
TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables;
report.Load(Server.MapPath("~/Reports/Monthly/CrMonthly.rpt"));
crConnectionInfo.ServerName = ConfigurationManager.AppSettings["Server4Crystal"].ToString();//[SQL SERVER NAME]
crConnectionInfo.DatabaseName = ConfigurationManager.AppSettings["Database4Crystal"].ToString();//[DATABASE NAME]
crConnectionInfo.UserID = ConfigurationManager.AppSettings["User4Crystal"].ToString();//[DB USER NAME]
crConnectionInfo.Password = ConfigurationManager.AppSettings["Password4Crystal"].ToString(); //[DB PASSWORD]
//LOOP THROUGH EACH TABLE & PROVIDE LOGIN CREDENTIALS
CrTables = report.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}
//PROVIDE PARAMETERS TO CRYSTAL REPORT, IF REQUIRED.
ParameterField paramField = new ParameterField();
ParameterFields paramFields = new ParameterFields();
ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();
paramField.Name = "PARAMETER_NAME";
paramDiscreteValue.Value = "PARAMETER_VALUE";
paramField.CurrentValues.Add(paramDiscreteValue);
paramFields.Add(paramField);
//ADD MORE PARAMETERS, IF REQUIRED....
StoreMonthlyViewer.ParameterFieldInfo = paramFields;
StoreMonthlyViewer.ReportSource = report;
//FINALLY REFRESH REPORT
StoreMonthlyViewer.RefreshReport();
StoreMonthlyViewer.ToolPanelView = CrystalDecisions.Web.ToolPanelViewType.None;
}

Well its not a big problem you just need to create session of your data source. Then pass it on page load. All crystal report function will work properly.
If you need any further help or code, let me know.

As stated in other answers kind of. Store the ReportDocument in a session (or something) and set the ReportSource.
Example:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ReportSource"] != null)
{
CrystalReportViewer1.ReportSource = (ReportDocument) Session["ReportSource"];
}
else
{
ReportDocument reportDocument = new ReportDocument();
reportDocument.Load("MyReport.rpt");
CrystalReportViewer1.ReportSource = reportDocument;
Session["ReportSource"] = reportDocument;
}
}

try looking for some parameter that your report does not contain
usually it happens when you insert some parameter in code and your report does not contain that parameter

Related

How to dynamically add a query in crystal report and where condition

How to dynamically add a query in crystal report and where condition to select record or column from multiple table and how to add field in crystal report
protected void Button1_Click(object sender, EventArgs e)
{
string sql = "select * from tblStudentFees";
ds = cc.ExecuteDataset(sql);
ReportDocument doc = new ReportDocument();
doc.Load(Server.MapPath("~/Andorid_Class_App/ReportFees.rpt"));
doc.SetDataSource(ds);
CrystalReportViewer1.ReportSource = doc;
}
You can pass your DataSet to crystal reports as you're doing with any query result set, so taking your example you'd just alter the query as per your requirements:
protected void Button1_Click(object sender, EventArgs e)
{
string sql = "select * from tblStudentFees
join sometable on tblStudents.sometable_id = sometable.id
where sometable.value = somecriteria";
DataSet ds = new DataSet();
ds = cc.ExecuteDataset(sql);
ReportDocument doc = new ReportDocument();
doc.Load(Server.MapPath("~/Andorid_Class_App/ReportFees.rpt"));
CrystalReportViewer1.ReportSource = doc;
CrystalReportViewer1.LocalReport.DataSources.Clear();
CrystalReportViewer1.DataSources.Add(
new Microsoft.Reporting.WebForms.ReportDataSource("DataSetIdentifier", ds)
);
}

how to map a checkbox to update the database after submit.

I need to use a the session dataTable email value for the #email and the base from the dropdownlist.
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.DataSource = (DataTable)Session["dt"];
DropDownList1.DataValueField = "base";
DropDownList1.DataTextField = "base";
DropDownList1.DataBind();
}
string str;
protected void Submit_Click(object sender, EventArgs e)
{
if (CheckBox9.Checked == true)
{
str = str + CheckBox9.Text + "x";
}
}
SqlConnection con = new SqlConnection(...);
String sql = "UPDATE INQUIRY2 set Question1 = #str WHERE email = #email AND Base = #base;";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#email", Session.dt.email);
cmd.Parameters.AddWithValue("#str", str);
cmd.Parameters.AddWithValue("#base", DropDownList1.base);
}
}
Your syntax for reading the value out of Session is wrong, you cannot use Session.dt.email.
You need to read the DataTable out of Session and cast it to a DataTable, like this:
DataTable theDataTable = null;
// Verify that dt is actually in session before trying to get it
if(Session["dt"] != null)
{
theDataTable = Session["dt"] as DataTable;
}
string email;
// Verify that the data table is not null
if(theDataTable != null)
{
email = dataTable.Rows[0]["Email"].ToString();
}
Now you can use the email string value in your SQL command parameters, like this:
cmd.Parameters.AddWithValue("#email", email);
UPDATE:
You will want to wrap your drop down list binding in Page_Load with a check for IsPostBack, because as your code is posted it will bind the drop down list every time the page loads, not just the first time, thus destroying whatever selection the user made.
Instead do this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DropDownList1.DataSource = (DataTable)Session["dt"];
DropDownList1.DataValueField = "base";
DropDownList1.DataTextField = "base";
DropDownList1.DataBind();
}
}
Now your base value in your database parameter logic should be the value the user selected.

I need a DropDown value that is linked to another page

I have a DropDown List where I have brought the values from my Database using code-behind.
I have added a new value after reading data from source, called ".. Add new skill".
Now when user clicks on that item I need a small page (or rather a new page) to open to add the skills that are not mentioned in the DropDownList.
if (!IsPostBack)
{
SqlConnection myConn = new SqlConnection(#"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True");
SqlCommand myCmd = new SqlCommand(
"SELECT SkillName, SkillID FROM Skills", myConn);
myConn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
//Set up the data binding.
DropDownList1.DataSource = myReader;
DropDownList1.DataTextField = "SKillName";
DropDownList1.DataValueField = "SkillID";
DropDownList1.DataBind();
//Close the connection.
myConn.Close();
myReader.Close();
//Add the item at the first position.
DropDownList1.Items.Insert(0, "..Add New Skill");
}
This is my code-behind file.. How do I link that now?
You should use the SelectedIndexChanged event and SelectedValue property:
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(String.Compare(ddl.SelectedValue,"..Add New Skill",true)==0)
Response.Redirect("Add_New_Skill.aspx");
}
Add a SelectedIndexChanged event handler to that dropdown like this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == 0)
Response.Redirect("Add_New_Skill.aspx");
}
If you want position of "...Add new skill" to be at last of the list
Use this
ddl.Items.Insert(ddl.Items.Count, "...Add New Skill");
Now to redirect to another page you should do this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == ddl.Items.Count-1)
Response.Redirect("Add_New_Skill.aspx");
}
Set AutoPostBack to true. That way when the user changes an option, it will automatically post the page to the server.
Handle this SelectedIndexChanged event, and redirect to your add page there.
Take your user to a add page.
Add the details to the database.
Bring the user back to this page.
List will be reloaded from database, and you till get your value.
No special linking is required.
This is working
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindDropdownlist()
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string getvalue = DropDownList1.SelectedItem.Value;
if (getvalue == "..Add New Skill")
{
Response.Redirect("Default.apsx");
}
}
public void bindDropdownlist()
{
SqlDataAdapter dap = new SqlDataAdapter("select coloumn1,colum2 from table", con);
DataSet ds = new DataSet();
dap.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "coloumn1";
DropDownList1.DataValueField = "colum2 ";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "..Add New Skill");
}
}
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</div>

CRUD Operations with DetailsView and EntityDataSource in Custom Server Control

I am not a big fan of ASPX pages, drag-and-drop and so on. I'm building a portal with a single Default.aspx and every other thing is custom web part controls or server controls that other developers can build in compiled dll and users can upload to the portal themselves to add features to the portal. I've been battling with DetailsView crud operations with entitydatasource. I did a test.aspx page with drag and drop and everything worked fine but with 100% code behind, nothing is. No error is displayed but data are not being persisted to database. I tried catching the onUpdating event of the detailsview and yes the event was fired and I could enumerate the data submitted but why is it not persisted to database? Hope someone can help with this.
Here's my code (trying to create everything from codebehind and add them to placeholders on the page just for testing purpose before I move everything to web part):
public partial class Test : System.Web.UI.Page
{
private EntityDataSource eds = new EntityDataSource();
public DetailsView dtlview = new DetailsView();
protected void Page_Load(object sender, EventArgs e)
{
//Initialize Datasource
eds.ConnectionString = "name=DBEntities";
eds.DefaultContainerName = "DBEntities";
eds.EnableDelete = true;
eds.EnableFlattening = false;
eds.EnableInsert = true;
eds.EnableUpdate = true;
eds.EntitySetName = "EmailAccounts";
Controls.Add(eds);//I don't know if this is necessary
//Create DetailsView and configure for inserting on default
dtlview.DataSource = eds;
dtlview.AutoGenerateInsertButton = true;
dtlview.AutoGenerateDeleteButton = true;
dtlview.AutoGenerateEditButton = true;
dtlview.AutoGenerateRows = false;
dtlview.DefaultMode = DetailsViewMode.Insert;
dtlview.AllowPaging = true;
dtlview.DataKeyNames = new string[] { "ID" };
dtlview.AllowPaging = true;
//Create fields since autogeneraterows is false
BoundField bfID = new BoundField();
bfID.DataField = "ID";
bfID.HeaderText = "ID:";
BoundField bfUserID = new BoundField();
bfUserID.DataField = "UserID";
bfUserID.HeaderText = "User ID:";
BoundField bfDisplayName = new BoundField();
bfDisplayName.DataField = "DisplayName";
bfDisplayName.HeaderText = "Display Name:";
BoundField bfEmailAddress = new BoundField();
bfEmailAddress.DataField = "EmailAddress";
bfEmailAddress.HeaderText = "Email:";
BoundField bfPassword = new BoundField();
bfPassword.DataField = "Password";
bfPassword.HeaderText = "Password:";
BoundField bfOutgoingServer = new BoundField();
bfOutgoingServer.DataField = "OutgoingServer";
bfOutgoingServer.HeaderText = "Outgoing server:";
BoundField bfIncomingServer = new BoundField();
bfIncomingServer.DataField = "IncomingServer";
bfIncomingServer.HeaderText = "Incoming Server:";
CheckBoxField chkfIsDefault = new CheckBoxField();
chkfIsDefault.DataField = "IsDefault";
chkfIsDefault.HeaderText = "Is Default?";
dtlview.Fields.Add(bfID);
dtlview.Fields.Add(bfUserID);
dtlview.Fields.Add(bfDisplayName);
dtlview.Fields.Add(bfEmailAddress);
dtlview.Fields.Add(bfPassword);
dtlview.Fields.Add(bfOutgoingServer);
dtlview.Fields.Add(bfIncomingServer);
dtlview.Fields.Add(chkfIsDefault);
dtlview.DataBind();
//Events handling for detailsview
dtlview.ItemInserting += dtlview_ItemInserting;
dtlview.ItemInserted += dtlview_ItemInserted;
dtlview.ModeChanging += dtlview_ModeChanging;
//Add controls to place holder
PlaceHolder2.Controls.Add(dtlview);
}
protected void dtlview_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
e.Values["UserID"] = GetCurrentUserID();
}
protected void dtlview_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
}
protected void dtlview_ModeChanging(object sender, DetailsViewModeEventArgs e)
{
dtlview.ChangeMode(e.NewMode);
if (e.NewMode != DetailsViewMode.Insert)
{
dtlview.DataSource = eds;
dtlview.DataBind();
}
}
}
I think what you have to do is add :
OnContextCreating="XXXXDatasource_OnContextCreating"
OnContextDisposing="XXXXDatasource_OnContextDisposing"
To your EntityDataSource.
Then in you code :
protected void XXXXDatasource_OnContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)
{
e.Context = DBEntities.Entities;
}
protected void XXXXDatasource_OnContextDisposing(object sender, EntityDataSourceContextDisposingEventArgs e)
{
e.Cancel = true;
}
That way, your ObjectContext is correctly set to the EntityDataSource used by your DetailsView.
At least that's what I read as best practice (also look up one object context per page request)

When does a page get rendered in ASP.NET?

I'm writing am ASP.NET/C# project, it's a simple blog page with commnents.
Problem I'm having when button click you see comments load original blogload plus blogs and comments, trying to get it to load blog/comment selected only.
If I try not to load blog in page_load or have it only do if not postback nothing is displayed. Any help would be appreciated.
PS I know there are many blog engines out there but have specific reason.
protected void Page_Init(object sender, EventArgs e)
{
//ParseControls(GlobalVar.pathxsltver);
// BindInfo();
}
private void ParseControls(string myxslt)
{
//load the data
FileStream fs = new FileStream(Server.MapPath ( GlobalVar.compathver), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
DataSet dset = new DataSet();
dset.ReadXml(fs);
fs.Close();
XPathDocument xdoc = new XPathDocument(Server.MapPath(GlobalVar.pathver ));
XmlDocument mydoc = new XmlDocument();
XPathNavigator navigator = xdoc.CreateNavigator();
XPathExpression expression = navigator.Compile("BlogItems/Blog");
expression.AddSort("ID", XmlSortOrder.Descending, XmlCaseOrder.UpperFirst, string.Empty, XmlDataType.Text);
XPathNodeIterator iterator = navigator.Select(expression);
int TheCnt = 0;
int cnt = GlobalVar.BlogCntDisplay;
string st = "<BlogItems>";
foreach (XPathNavigator item in iterator)
{
TheCnt++;
string sid = item.SelectSingleNode("ID").Value;
st = st + "<Blog id=\"" + sid + "\">" + item.InnerXml;
st = st + "<ComCnt>" + MyFunc.CountComments (sid,dset) + "</ComCnt></Blog>";
if (TheCnt == cnt) { break; }
}
st = st + "</BlogItems>";
mydoc.LoadXml(st);
XslCompiledTransform transform = new XslCompiledTransform();
XsltSettings settings = new XsltSettings(true,true);
transform.Load(Server.MapPath(myxslt),settings,null);
StringWriter sw = new StringWriter();
transform.Transform(mydoc, null, sw);
string result = sw.ToString();
//remove namespace
result = result.Replace("xmlns:asp=\"remove\"", "");
//parse control
Control ctrl = Page.ParseControl(result);
//find control to add event handler
//Boolean test = phBlog.FindControl("btnComment2").i;
phBlog.Controls.Add(ctrl);
XmlNodeList nList = mydoc.SelectNodes("//BlogItems/Blog/ID");
foreach (XmlNode objNode in nList)
{
Button btnComment = (Button) phBlog.FindControl("btnComment"+objNode.InnerText );
btnComment.CommandArgument = objNode.InnerText ;
btnComment.BorderWidth = 0 ;
btnComment.Command += new CommandEventHandler(Button1_Click);
}
}
protected void Page_Load(object sender, EventArgs e)
{
//if (!Page.IsPostBack )
//{ParseControls(GlobalVar.pathxsltver);}
ParseControls(GlobalVar.pathxsltver);
}
protected void Button1_Click(object sender, CommandEventArgs e)
{
Label1.Text = "Comm hit : " + e.CommandArgument.ToString();
ParseControls(GlobalVar.blogcommentsver );
}
You're question is kind of vague, but if I understand you correctly, you're wondering why the entire page refreshes when you just want to handle the button click?
Whenever you do any kind of postback, and that includes handling any events, the entire page is re-rendered. More than that, you're working with a brand new instance of your page class. The old one is dead and gone. That's just the way the web normally works.
If you only want to reload a part of the page, you need to use ajax. In ASP.Net land, that means placing your comments section inside an UpdatePanel control that can be refreshed.

Resources