Reportviewer not displaying report properly - reportviewer

EDIT: I made it so I'm executing a sql statement instead of stored procedure, just for debugging. I now have an error: A data source instance has not been supplied for the data source 'DataSet2'. I also got rid of ReportViewer1.Reset();
I'm trying to figure out why my reportviewer isn't displaying a report like it should after the user clicks on the button "RunReportButton" on Reports.aspx. I have a sql statement that has 2 parameters: #PersonID and #Category. this sql statement searches all records in PersonExercise table that have PersonID = #PersonID And #Category = Category. I execute a dataset based on this sql statement and then pass that into my reportDataSource in the code behind of my reports.aspx.
I then created Report1.rdlc and linked that up to my dataset dsCardio. I dragged ExerciseDate, Distance, Speed from my dataset onto a matrix on Report1.rdlc. When the user clicks on RunReportButton on Reports.aspx then I get the following error: "A data source instance has not been supplied for the data source 'DataSet2'". I debugged my code and I saw that thisDataSet.Tables[0].Rows.Count = 3, which it should. I also have processingmode = local for reportviewer. Any help? Thanks so much!
Here is my Reports.aspx markup that has the reportviewer:
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Cardiovascular</asp:ListItem>
<asp:ListItem>Weight Lifting</asp:ListItem>
</asp:DropDownList>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Button ID="RunReportButton" runat="server"
onclick="RunReportButton_Click1" Text="Run Report" Height="27px"
Width="84px" />
<rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana"
Font-Size="8pt" InteractiveDeviceInfos="(Collection)"
WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt"
Visible="False">
<LocalReport ReportPath="Report1.rdlc">
</LocalReport>
</rsweb:ReportViewer>
</asp:Content>
Here is Reports.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.ApplicationBlocks.Data;
using Microsoft.Reporting.WebForms;
using System.Data.SqlClient;
using System.Data;
using System.Data.Common;
using System.Data.Sql;
using System.Configuration;
namespace ExerciseTracker2000
{
public partial class Reports : System.Web.UI.Page
{
#region Properties
public static string ConnectionString { get; set; }
public static int personID { get; set; }
#endregion
#region Variables
public int personID = 0;
public SqlParameter[] SearchValue = new SqlParameter[2];
#endregion
#region Page Events
protected void Page_Load(object sender, EventArgs e)
{
personID = CommonMethods.getLoggedInUser();
}
protected void RunReportButton_Click1(object sender, EventArgs e)
{
try
{
DataSet ds = new DataSet();
string strCategory = ddlCategory.SelectedValue;
// strSQL select for orders with no invoices
strSQL = "SELECT PersonID, ExerciseDate, Category, Exercise, Duration, Distance, Speed";
strSQL = strSQL + " from dbo.PersonExercise";
strSQL = strSQL + " where PersonID = " + personID + " And Category = '" + strCategory + "'";
using (var connection = new SqlConnection(ConnectionString))
{
SqlDataAdapter ad = new SqlDataAdapter(strSQL, connection);
ad.Fill(ds, "Table0");
}
//ReportViewer1.Visible is set to false in design mode
ReportViewer1.Visible = true;
SqlConnection thisConnection = new SqlConnection(ConnectionString);
/* Associate thisDataSet (now loaded with the stored
procedure result) with the ReportViewer datasource */
Microsoft.Reporting.WebForms.ReportDataSource datasource = new
Microsoft.Reporting.WebForms.ReportDataSource("DataSetCategories_ShowExercisesByCategory", ds.Tables[0]);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);
if (thisDataSet.Tables[0].Rows.Count == 0)
{
lblMessage.Text = "Sorry, no products under this category!";
}
ReportViewer1.LocalReport.Refresh();
}
catch (Exception ex)
{
lblMessage.Text = "Error: " + ex.Message.ToString();
}
}
#endregion
}
}

Where is your Path to the report
ReportViewer1.LocalReport.Path = "Report1.rdlc";
EDIT: Nevermind, I see it in the XAML
EDIT2: You call ReportViewer1.Reset(); This is clearing the LocalReport. You have to set the report path again.

Related

Check if user input into a ASP.net webform Textbox exists in a SQL column

How can I validate the user input to a data in a SQL table?
I want to ensure the users can only input Part Numbers that are in a SQL table.
It is a Web form in ASP.net.
private static List<string> AutoFillProducts(string prefixText)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "select PART from PARTSTABLE where " + "LOWER (PART) like #Search + '%'";
com.Parameters.AddWithValue("#Search", prefixText);
com.Connection = con;
con.Open();
List<string> parts = new List<string>();
using (SqlDataReader sdr = com.ExecuteReader())
{
while (sdr.Read())
{
parts.Add(sdr["PART"].ToString());
}
}
con.Close();
return parts;
}
}
}
<asp:TextBox ID="txtpart" runat="server" Height="30px" input type="text" placeholder="Enter Part" style="text-transform:uppercase;" onblur="onLeave(this)" OnTextChanged="txtpart_TextChanged"></asp:TextBox>
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="4"
CompletionInterval="5" EnableCaching="false" CompletionSetCount="1" TargetControlID="txtpart"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">
</asp:AutoCompleteExtender>

The Microsoft Access database engine cannot open or write to the file

I have the following function:
Public Function OleDBCSVToDataTable(directory As String, tableName As String, fileName As String, Optional start As Long = 0) As DataTable
Dim CnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & directory & ";Extended Properties='Excel 8.0;HDR=YES'"
Dim dt As DataTable = GetTableSchema(tableName)
Using Adp As New OleDbDataAdapter("select * from [" & fileName & "]", CnStr)
Adp.Fill(start, 1000, dt)
End Using
Return dt
End Function
The function is designed to read a CSV into a data table using OLEDB for import into SQL, however I am receiving this error:
"The Microsoft Access database engine cannot open or write to the file
'C:\TEST'. It is already opened exclusively by another user, or you
need permission to view and write its data."
I have attempted this solution. All permissions have been granted (permissions are Full Control across users):
I have seen this solution as well, however, the proposed options other than OLEDB are solutions that don't seem to work with CSV. Besides, I imagine there are native libraries.
I am open to suggestions for better ways to accomplish this, however, based on requirements - large CSVs, data validation - this appears to be the best, assuming I am able to get it working.
How about importing the CSV file into a DataGridView, and then exporting from that object into MS Access?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Globalization;
using System.Configuration;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
string delimiter = ",";
string tablename = "medTable";
DataSet dataset = new DataSet();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (MessageBox.Show("Are you sure you want to import the data from \n " + openFileDialog1.FileName + "?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
filename = openFileDialog1.FileName;
StreamReader sr = new StreamReader(filename);
string csv = File.ReadAllText(openFileDialog1.FileName);
dataset.Tables.Add(tablename);
dataset.Tables[tablename].Columns.Add("Order ID");
dataset.Tables[tablename].Columns.Add("Product");
dataset.Tables[tablename].Columns.Add("Unit Price");
dataset.Tables[tablename].Columns.Add("Quantity");
dataset.Tables[tablename].Columns.Add("Discount");
string allData = sr.ReadToEnd();
string[] rows = allData.Split("\r".ToCharArray());
foreach (string r in rows)
{
string[] items = r.Split(delimiter.ToCharArray());
dataset.Tables[tablename].Rows.Add(items);
}
this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
MessageBox.Show(filename + " was successfully imported. \n Please review all data before sending it to the database.", "Success!", MessageBoxButtons.OK);
}
else
{
this.Close();
}
}
}
public string filename { get; set; }
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void Import_Load(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
//remove the semicolon, and add brackets below after line
{
//create the connection string
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Ryan\\Desktop\\Coding\\Microsoft Access\\Northwind_2012.mdb";
//create the database query
string query = "SELECT * FROM [OrderDetailsTest]";
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
//the DataGridView
DataGridView dataGridView1 = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dataGridView1.DataSource = bSource;
// An update function to get the changes back into the database.
dAdapter.Update(dTable);
}
}
}

export table sql to .txt with c#

I think I have a fairly simple question. I just need to know how to export fields from a table in an sql database using either asp.net or C#? Anyway to do this would be good.
I suppose I am looking for something like this, but perhaps simpler:
Export values from SQL Server to txt file
Whatever the case, I am trying to get values from a database to a .txt, like by pressing a button in asp.net or C#, based on criteria (like between certain dates, from a date field, or starting at a certain date with a certain user, and exporting a certain number of them). Any suggestions would help.
If I used the following code, what would I need to change so that if I wanted to select a certain column, like Note, in the database, and Date column, what would I need to do?
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class ExportText : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYLearningConnectionString"].ConnectionString);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from tblUsers", conn);
DataSet ds = new DataSet();
da.Fill(ds);
ExportToText(ds.Tables[0], "DataTable");
}
protected void ExportToText(DataTable dataTable, string fileName)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in dataTable.Columns)
{
context.Response.Write(column.ColumnName + ",");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in dataTable.Rows)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
context.Response.Write(row[i].ToString() + ",");
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + ".txt");
context.Response.End();
}
}

I get an error in my code

I got an error
Incorrect syntax near '.'. Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using System.Threading;
namespace Cloths_Inventory
{
public partial class frmBackup : Form
{
//DataTable dtServers = SmoApplication.EnumAvailableSqlServers(true);
//private static Server srvr;
//private string DBpath = Application.StartupPath;
public frmBackup()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bool bBackUpStatus = true;
Cursor.Current = Cursors.WaitCursor;
if (Directory.Exists(#"D:\SQLBackup"))
{
if (File.Exists(#"D:\SQLBackup\wcBackUp1.bak"))
{
if (MessageBox.Show(#"Do you want to replace it?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
File.Delete(#"D:\SQLBackup\wcBackUp1.bak");
}
else
bBackUpStatus = false;
}
}
else
Directory.CreateDirectory(#"D:\SQLBackup");
if (bBackUpStatus)
{
//Connect to DB
SqlConnection connect;
string con = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Garment.mdf;Integrated Security=True;Asynchronous Processing= True ;User Instance=True";
connect = new SqlConnection(con);
connect.Open();
//Execute SQL---------------
SqlCommand command;
command = new SqlCommand(#"backup database Garment.mdf to disk ='E:Garment.bak' with init,stats=10", connect);
command.ExecuteNonQuery();
//--------------
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
You cannot use the AttachDbFileName= approach and then use a server-based command like backup database....
If you want to back up your SQL Server database, it has to be attached to the server, and you need to connect to the server and issue that command:
// Connect to "master" database
string con = #"server=.\SQLEXPRESS;database=master;Integrated Security=True;";
SqlConnection connect = new SqlConnection(con);
SqlCommand ommand = new SqlCommand(#"backup database Garment to disk = N'E:\Garment.bak' with init,stats=10", connect);
connect.Open();
command.ExecuteNonQuery();
connect.Close();
You are missing a backslash E:Garment.bak should be E:\Garment.bak
command = new SqlCommand(#"backup database Garment.mdf to disk ='E:\Garment.bak' with init,stats=10", connect);

Getting the values of a dynamically created control inside Telerik:RadGrid

I have a telerik RadGrid to which I am adding columns dynamically on click of a button. The Code is as follows :
private void AddColumns()
{
try
{
DataTable dtParMaintenanceListHeaderData = (DataTable)Session["ParMaintenanceListHeaderData"];
foreach (DataColumn dc in dtParMaintenanceListHeaderData.Columns)
{
dc.ReadOnly = false;
}
if (!dtParMaintenanceListHeaderData.Columns.Contains("parComboDataField"))
dtParMaintenanceListHeaderData.Columns.Add("parComboDataField", typeof(string));
dtParMaintenanceListHeaderData.AcceptChanges();
foreach (DataRow drEachRow in dtParMaintenanceListHeaderData.Rows)
{
string cusCombo = drEachRow["cusfstnam"].ToString() + " - " + drEachRow["cuslstnam"].ToString();
string parCombo = drEachRow["parcod"].ToString() + " - " + drEachRow["pardsc"].ToString();
drEachRow["parComboDataField"] = cusCombo + " " + parCombo;
GridTemplateColumn templateColumn = new GridTemplateColumn();
string templateColumnName = cusCombo + " - " + parCombo;
templateColumn.ItemTemplate = new RadGridTemplate(templateColumnName);
templateColumn.HeaderText = templateColumnName;
templateColumn.DataField = "parqty";
templateColumn.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
templateColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
templateColumn.HeaderStyle.Width = Unit.Pixel(60);
templateColumn.HeaderStyle.Wrap = true;
this.radgridParListItems.MasterTableView.Columns.Add(templateColumn);
}
}
catch (Exception Ex)
{
}
}
The above method is called on click of a button.
In each of the columns added I am adding a textbox as follows :
#region Namespaces used
using System;
using System.Web;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Telerik.Web.UI;
#endregion
/// <summary>
/// Summary description for RadGridTemplate
/// </summary>
public class RadGridTemplate : ITemplate
{
protected LiteralControl lControl;
protected TextBox textBox;
private string colname;
public RadGridTemplate(string cName)
{
colname = cName;
}
public void InstantiateIn(System.Web.UI.Control container)
{
textBox = new TextBox();
textBox.ID = container.ID + "txtParQty";
textBox.Width = Unit.Pixel(50);
container.Controls.Add(textBox);
textBox.Text = HttpContext.Current.Request.Form[textBox.UniqueID];
}
}
Now there is another button,"Save" which when clicked upon will have to fetch the data from all the textboxes in the dynamically added controls. The trouble is :
On post back all the controls are cleared and re-created so their values are null.
How do I capture the values of all the textboxes in a row.
If you instantiate the template columns on init as explained in the telerik docs here, you should be able to keep their state steady on posbacks and fetch the data from the textboxes looping through the grid rows.
I am adding the solution for the use of other users who are all facing same problem.
To avoid recreation of dynamic controls in radgrid we have to call the set EnableColumnsViewState="false" in MasterTableView of the grid. It worked for me.
Regards,
Nathiya Rajendran.