RDLC Report Viewer - How to reset the input parameters programmatically - asp.net

I have a RDLC control on my website. This is client side report. I am using ASP.net 3.5 with Visual Studio 2010 There are a number of filtering criteria which the report takes as the input parameters. There is a SQl server 2008 R2 Stored Procedure which generates the results. One of the inputs is a datetime textbox with associated calendar control. There is a 'Refresh' button. Clicking this refreshes the report. I wanted to add some validations for date. All my validations work fine. My issue is when a user enters wrong characters in the datetime textbox, the report fails which is correct but when the user hits refresh button though the error vanishes the report still displays the error message.
Is there a way to refresh the parameters when locally calling the report.
This is my simple code -
protected void BtnRefresh_Click(object sender, EventArgs e)
{
//check object session
LoginSessionData.IsValid();
//Hide the display panel
DisplayMessage.Visible = false;
//add a try catch block here
try
{
ReportViewer1.LocalReport.Refresh();
}
catch (Exception ex)
{
m_logger.Error(ex);
}
}

You can set parameter values to blank or otherwise using this:
ReportParameter p1 = new
ReportParameter("ShowDescriptions", checkBox1.Checked.ToString());
ReportParameter p2 = new
ReportParameter("MyDate", DateTime.Now.ToString());
ReportViewer1.LocalReport.SetParameters(new ReportParameter[] { p1, p2 });

Related

radGrid control displays blank grid after date parameter is changed

I searched SO, google & Telerik forums, but could not find a solution.
I have an existing app (written by a previous developer) that is calling a stored procedure that populates a RadGrid control. It populates fine the first time around.
However, when I change the date parameter, click "search" button, I get a blank RadGrid control. When I click search the second time, the grid is populated. When I walk through the code, I get an error message
Column 'ID' does not belong to table Table.
How can I resolve the issue of having to click search twice to display data ?
My code behind is:
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
try
{
ViewState["newset"] = null;
CreateDatasource();
this.RadGrid1.DataBind();
this.RadGrid1.CurrentPageIndex = 0;
ViewState["newset"] = "new";
string idex = this.hdnindex.Value;
if (idex != string.Empty)
this.RadGrid1.MasterTableView.Items[int.Parse(idex)].Selected = true;
}
catch (Exception ex) {
this.lblMessage.Text = ex.Message;
}
}
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
try
{
if (e.Item is GridDataItem)
{
GridDataItem item = (GridDataItem)e.Item;
HyperLink hLink = (HyperLink)item["ViewHyperLink"].Controls[0];
if (hLink != null)
hLink.Attributes.Add("onclick", "selectMe('" + item.ItemIndex + "');");
}
}
catch (Exception ex)
{
this.lblMessage.Text = ex.Message;
}
}
In the code behind above, when this.RadGrid1.DataBind() is called, the code steps into RadGrid1_ItemCreated loops through the if statement a few times, them goes into the if statement, comes out of the function, and then the catch statement of btnSubmit is called, which displays the error message "Column ID does not belong to table Table".
Any ideas on how to resolve this?
Maybe you should try Grid - Simple Data Binding. Also you this thread (RadGrid NeedDataSource Page load) on telerik forum talks in detail about Simple Data binding. I don't know if you are trying to use NeedDataSource, but I have had similar issues before and the Simple Data binding worked perfectly.
That sure sounds like to me you need to call RadGrid1.Rebind() somewhere. Try calling that for your last line in your try block inside btnSubmit_OnClick.
Also, what does this search button do? Does it filter the results based on a date?

How can I pass parameter to Reportviewer?

I am trying to create report for TOP (according to user provide say 10,100,200..) products. I am 90% success with it. Now, I am finding difficulties to show this numbers to Report header. So, my report header is saying Top Products, now I want to make this dynamic, saying Top 100 Products, Top 200 Products.
I AM USING VS 2008.
For this, I created parameter in ReportViewer. I tried this code in Page_Load event ;
protected void Page_Load(object sender, EventArgs e)
{
ReportDataSource rds = new ReportDataSource("SP_GetProductsbySales_DataSet");
//ReportViewer1.ServerReport.ReportPath = "Report1.rdlc";
ReportViewer1.LocalReport.ReportPath = "Report1.rdlc";
ReportParameter[] param = new ReportParameter[1];
param[0] = new ReportParameter("top", "100");
ReportViewer1.ServerReport.SetParameters(param);
ReportViewer1.ServerReport.Refresh();
}
but getting error saying : The source of the report definition has not been specified.
How can I accomplish this one? I tried to google as well as watched some videos, but still I am not getting any idea.
Thanks.
Please set data source
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rds);
You can set an expression in your report to show the value.
The expression would be as follows:
="Top " & Parameters!top.Value & " Products"

Asp.Net SQL Refresh page duplicate inserts?

I have a *.aspx page that contains a text box and a button. When the user enters information in to the textbox and clicks post, it inserts the data into my sql database. The issue is, that if the user hits refresh, it will keep inserting the same data into the database. I am pretty sure the whole "click" method is called, not just the insert call. I tried messing with sessions but it complains. I am not really sure what to do. I am looking for a simple easy fix.
protected void PostButton_Click(object sender, EventArgs e)
{
string wpost = (string)Session["WallPost"];
DateTime wtime = (DateTime)Session["WallDateTime"];
if (txtWallPost.Text.Length > 0 && !wpost.Equals(txtWallPost.Text))
{
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strCon))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO [WallTable] ([UserId], [FriendId], [WallPost]) VALUES (#UserId, #FriendId, #WallPost)";
cmd.Parameters.AddWithValue("#UserId", User.Identity.Name);
cmd.Parameters.AddWithValue("#FriendId", User.Identity.Name);
cmd.Parameters.AddWithValue("#WallPost", txtWallPost.Text);
conn.Open();
cmd.ExecuteNonQuery();
Session.Add("WallPost", txtWallPost.Text);
Session.Add("WallDateTime", new DateTime());
conn.Close();
txtWallPost.Text = "";
LoadWallPosts();
}
}
}
return;
}
If the PostButton_Click is the server handler for the click event on your button then insert code shold be executed only if the user hits the post button - it should not happen in case of refresh.
I am pretty sure is not enough - to be sure put a breakpoint in your PostButton_Click method, hit F5 to run in debug mode and see if the breakpoint gets hit with a refresh.
If so it means that:
you are calling explicitly
PostButton_Click from somewhere
else (Page_Load?)
PostButton_Click was accidentally
set as event handler for some other
event on the page
A quick way of verifying hypotesis 1 & 2 is to run a search for PostButton_Click and see where you are calling it from or if it set as handler for some other element (maybe your form?) in the markup.
Add Response.Redirect(Request.Url.ToString(), false); to your button event and that should solve the problem.
if he refreshes or press the back button the post will happen again, thus your page will process the same data thus insert once again.
You have to change your logic
It would be preferable to redirect the client to another page after the insert, however, if you really need the client stay in the same page, you can use a (bool) variable on your page to state if the insert has been done, and skip the insert logic if it has been executed before

Asp.Net on refresh, a duplicate post is inserted...should only be one post

I have a asp:textbox that allows a user to enter information. When the user clicks the asp:button, it inserts the text from the textbox into my sql database, and then redirects back to the page. If the user hits refresh, the event from the button gets called again. I need to rectify this so that it no longer gets called or it doesn't repost the information.
protected void PostButton_Click(object sender, EventArgs e)
{
if (txtWallPost.Text.Length > 0)
{
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strCon))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO [WallTable] ([UserId], [FriendId], [WallPost]) VALUES (#UserId, #FriendId, #WallPost)";
cmd.Parameters.AddWithValue("#UserId", User.Identity.Name);
cmd.Parameters.AddWithValue("#FriendId", User.Identity.Name);
cmd.Parameters.AddWithValue("#WallPost", txtWallPost.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
txtWallPost.Text = "";
LoadWallPosts();
Response.Redirect("~/UserPages/UserProfile.aspx?view="+"wall");
}
}
}
return;
}
Classic problem, with a classic solution: Redirect After Post. You just need to redirect the user to another page (or the same page...) after processing the POST - that way when they hit refresh, the last request (and the one to be repeated) will be a GET.
See:
Refresh the page after a postback action in asp.net
How do I use the “Post/Redirect/Get” a.k.a. “Redirect after Post” with asp.net
Page Refresh Causes Duplicate POST in ASP.NET Applications
Curing the “Back Button Blues”
I ended up just adding a session id for the wall post text. In the post method, it checks to make sure the textbox text, is different from that of the session text. On refresh it clears out the session and therefore works fine.

ASP.NET Formview Item Inserting Event

I'm using the FormView control in ASP.NET for a simple form to insert into a MS SQL DB. I have an event for onItemInserting to set some values behind (such as time stamp, etc) and was curious how to check some user entered values in the onItemInserting event and cancel the item from being inserted. The reason I want to do it in the code behind is to query the database and use the values to validate the user entered data.
Pseudo Code is as follows:
protected void Form_addRoom_ItemInserting(object sender, FormViewInsertEventArgs e)
{
... Query DB for some values ...
if(enteredMaxPeople > queryMaxPeople)
{
**Cancel** DB Insert
statusLabel.text = "Value entered not valid";
}
}
In the end the question comes down to how do I cancel a FormView from inserting in the code behind?
Thank you!
Sean
e.Cancel = true;

Resources