How can I pass parameter to Reportviewer? - asp.net

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"

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?

RDLC Report Viewer - How to reset the input parameters programmatically

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

issues displaying latest news from database onto my website

I am having problems in setting a up a latest news panel on my website.
Currently
public System.Data.SqlClient.SqlConnection Admin_conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectString"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = News();
if (dt.Rows.Count > 0) // Check if the DataTable returns any data from database
{
lbltest.Text = dt.Rows[0]["NewsTitle"].ToString();
lblDate.Text = dt.Rows[0]["NewsDate"].ToString();
lbldescription.Text = dt.Rows[0]["NewsDescription"].ToString();
}
}
protected DataTable News()
{
DataTable dt = new DataTable();
SqlDataAdapter data = new SqlDataAdapter("SELECT NewsTitle, NewsDescription, NewsDate FROM News WHERE [NewsDate] < getdate()", Admin_conn);
data.Fill(dt);
return dt;
}
But the above code just display news of single row.. I want to display all the news on my website. Which control should I use to display all the records from the database in a proper order like news title, news description then the next news title and description.....
Is there any way to use ajax accordion so that all the news title will be displayed and when I click on the specific news title, the description of that news will be displayed.
Any suggestions or tutorial will be highly appreciated..
I believe you are looking for the ListView Control.
It will allow you to bind to the entire set of rows being returned from the database and provide a template for each item.
You can also take a few minutes to watch this video tutorial from Microsoft:
The ListView Control: The Official Microsoft ASP.NET Site

ASP.net DataTable doesn't store new rows

In my simple starter asp page I create a DataTable and populate it with two rows. The web site allows users to add new rows. My problem is the DataTable doesn't save the information. I've stepped through the code and the row gets added but the next time a row is added it's not there, only the original two and the newest one to get entered.
I have gotten around this, in an inelegant way, but am really curious why the new rows are being saved.
My code:
protected void Page_Load(object sender, EventArgs e)
{
_Default.NameList = new DataTable();
DataColumn col = new DataColumn("FirstName", typeof(string));
_Default.NameList.Columns.Add(col);
col = new DataColumn("LastName", typeof(string));
_Default.NameList.Columns.Add(col);
DataRow row = _Default.NameList.NewRow();
row["FirstName"] = "Jane";
row["LastName"] = "Smith";
_Default.NameList.Rows.Add(row);
row = _Default.NameList.NewRow();
row["FirstName"] = "John";
row["LastName"] = "Doe";
_Default.NameList.Rows.Add(row);
}
protected void AddButton_Click(object sender, EventArgs e)
{
DataRow row = _Default.NameList.NewRow();
row["FirstName"] = this.TextBox1.Text;
row["LastName"] = this.TextBox2.Text;
_Default.NameList.Rows.Add(row);
_Default.NameList.AcceptChanges(); // I've tried with and without this.
}
I've tried saving them to GridView control but that seems like quite a bit of work.
I'm new to ASP.Net but have done windows programming in C# for the last two years.
You're creating a new DataTable object each time the page loads.
You need to persist the DataTable object to session state or a static variable, or save the data to a database.
Remember that handling events like your button click requires a full postback. You don't run just the click code, you run your entire page lifecycle on a new instance of your page class. The new instance of your page class means a new instance of the datatable as well.
The issue here is that your DataTable is being created every time your page loads and it goes out of scope when your page has finished loading and been displayed to the user. To get your desired effect, you will need to store the DataTable in either Session, ViewState, cache, use a control like GridView that will automatically store the underlying data in its state, or something else.
Since you're new to ASP.NET, check out your options for state management.

Use of SqlCommandBuilder in ASP.NET

I have used the following code to add the feedback entered to the web form into a database.
The code works fine. But when I try to deleted thi statement
SqlCommandBuilder objcb = new SqlCommandBuilder(objDa);
I am getting an error I mean it is executing the else part.
Can any one tell me what is the use of SqlCommandBuilder?
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtName.Text.Trim() == "")
{
Response.Write("<script>alert ('Name Field cannot be left blank')</script>");
return;
}
if (txtFeedBack.Text.Trim() == "")
{
Response.Write("<script>alert('FeedBack Field cannot be left blank')</script>");
return;
}
objSqlConnection.ConnectionString = connectionStringSetting;
objSqlConnection.Open();
try
{
SqlDataAdapter objDa = new SqlDataAdapter("select * from FeedBack", objSqlConnection);
SqlCommandBuilder objcb = new SqlCommandBuilder(objDa);
DataSet objDs = new DataSet("FeedBack");
objDa.Fill(objDs, "FeedBack");
DataRow dr = objDs.Tables["FeedBack"].NewRow();
dr[1] = txtName.Text;
dr[2] = txtAddress.Text;
dr[3] = txtCity.Text;
dr[4] = txtCountry.Text;
dr[5] = txtEmail.Text;
dr[6] = Convert.ToInt32(txtContactNo.Text);
dr[7] = txtFeedBack.Text;
objDs.Tables["FeedBack"].Rows.Add(dr);
objDa.Update(objDs, "FeedBack");
Response.Write("<script>alert('Your FeedBack has been submitted')</script>");
objSqlConnection.Close();
}
catch (Exception)
{
Response.Write("<script> alert('Error on Page. Please try after sometime')</script>");
objSqlConnection.Close();
}
And is there any way to display the specific error messages like if an user enters a string value instead of Integer value it should display the message as 'Input String not entered in correct format?
Never use catch (Exception). It hides the problem. If an exception is being thrown, then there's something serious wrong. You need to learn about it.
Remove the entire try/catch block (keep the code inside it!). Then run your code again. If there's an exception, then you'll see it on the error page. If not, then use the Event Viewer to look in the Windows Event Log for a warning message from the "ASP.NET" source. It should contain the complete exception.
Final answer is that the line you are talking out is doing a bunch of stuff in the background.
It is adding the insert, update and delete commands to the DataAdapter. So without it, you will crash and burn, unless you add those commands yourself to the DataAdapter.

Resources