Reportviewer memory leak C# - c#

When printing the receipt through the reportviewer memory leakage is arising. Even though I have tried other solutions mentioned non of it didn't give me any positive outcome.
I have run the garbage collector but still did not get any outcome properly. Please give me a proper solution to sort out the matter.
static string myconn = ConfigurationManager.ConnectionStrings["connstrng"].ConnectionString;
SqlConnection conn = new SqlConnection(myconn);
readonly SalesF sf;
public RecieptForm(SalesF frm)
{
InitializeComponent();
this.sf = frm;
}
private void RecieptForm_Load(object sender, EventArgs e)
{
this.reportViewer1.RefreshReport();
}
public void LoadReceipt(string cashTendered, string cashBalance)
{
ReportDataSource receiptds;
try
{
this.reportViewer1.LocalReport.ReportPath = Application.StartupPath + #"\Reports\CashPaymentReciept.rdlc";
this.reportViewer1.LocalReport.DataSources.Clear();
DataSet1 dc = new DataSet1();
SqlDataAdapter sda = new SqlDataAdapter();
string query = "select c.id,c.transno,c.productid,c.price,c.quantity,c.total,c.transactiondate,p.description from tbl_cart as c inner join product as p on p.productID=c.productid where transno like '" + sf.lblInvoiceNumber.Text + "'";
conn.Open();
sda.SelectCommand = new SqlCommand(query, conn);
sda.Fill(dc.Tables["dtSold"]);
sda.Dispose();
dc.Dispose();
ReportParameter cartTotal = new ReportParameter("cartTotal", sf.lblAmount.Text);
ReportParameter cashTend = new ReportParameter("cashTendered", cashTendered);
ReportParameter cashBal = new ReportParameter("cashBalance", cashBalance);
ReportParameter storeName = new ReportParameter("storeName", store.ToUpper());
ReportParameter cashier = new ReportParameter("cashier", "Cashier: " + sf.lblName.Text);
reportViewer1.LocalReport.SetParameters(cartTotal);
reportViewer1.LocalReport.SetParameters(cashTend);
reportViewer1.LocalReport.SetParameters(cashBal);
reportViewer1.LocalReport.SetParameters(storeName);
reportViewer1.LocalReport.SetParameters(cashier);
receiptds = new ReportDataSource("DataSet1", dc.Tables["dtSold"]);
reportViewer1.LocalReport.DataSources.Add(receiptds);
reportViewer1.LocalReport.PrintToPrinter();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sf.Refresh();
reportViewer1.Dispose();
GC.SuppressFinalize(reportViewer1);
conn.Close();
conn.Dispose();
}
}

Related

How create Charts in SubReport in reportviewer

I try create a pdf with a subreport and a chart into subreport, when i create pdf, this error show:
The subreport 'Subreport' could not be found at the specified location
~\ReciboCargoConceptos.rdlc. Please verify that the subreport has been
published and that the name is correct.
.... I add subProcessingEvent
var appDomain = AppDomain.CurrentDomain;
var basePath = appDomain.RelativeSearchPath ?? appDomain.BaseDirectory;
var path = Path.Combine(basePath, "Vistas", "ReciboTres" + ".rdlc");
var reporteLocal = new ReportViewer();
reporteLocal.Reset();
reporteLocal.LocalReport.DataSources.Clear();
if (File.Exists(path))
reporteLocal.LocalReport.ReportPath = path;
var utils = new Utils();
DataTable dt = GetResult();
reporteLocal.LocalReport.DataSources.Add(new ReportDataSource("DSRecibo", dt));
reporteLocal.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(CargoConceptoSubReport);
Method SubreportProcessingReport
void CargoConceptoSubReport(object sender, SubreportProcessingEventArgs e)
{
int idContrato = int.Parse(e.Parameters["IdContrato"].Values[0]);
var dtGrafica= GetGrafica(idContrato);
ReportDataSource datasource= new ReportDataSource("Grafica", dtGrafica);
e.DataSources.Add(datasource);
}
Method GetGrafica
private DataTable GetGrafica(int id)
{
DataTable resultTable = new DataTable();
SqlConnection conn = new SqlConnection("ConnectionString");
try
{
using (conn)
{
string query = #"select top 24 Consumo.ConsumoAgua, PeriodoFacturacion.FechaFinal, PeriodoFacturacion.Id from Consumo inner join PeriodoFacturacion on " +
"PeriodoFacturacion.Id = Consumo.IdPeriodoFacturacion where Consumo.IdContrato = " + id + " order by PeriodoFacturacion.FechaFinal desc";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
resultTable.Load(reader);
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
return resultTable;
}
PDF With Error SubReport With Chart:

Database access from within asp.net C# web sitie

I have an asp.net web site I'm trying to develop and I have an issue loading data from a database. It worked fine in a C# WebForm App and I was wondering what i need to do to get it to work correctly in the asp.net project and bind the results to a dropdownlist to be selected from.
try
{
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder
{
DataSource = "127.0.0.1",
InitialCatalog = "PIIMSDATA",
IntegratedSecurity = true
};
SqlConnection cs = new SqlConnection(connectionStringBuilder.ToString());
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Book1 Order by ID", cs);
}
System.Data.DataTable dt = new System.Data.DataTable();
da.Fill(dt);
//DropDownList2.DataSource = ds.Tables[0];
//DropDownList2.DataTextField = "ID";
//DropDownList2.DataValueField = "ID";
//DropDownList2.DataBind();
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex + "');", true);
//MessageBox.Show(ex.Message);
}
}
There are many ways to do that. Here's an example that I've ever tried:
public string connectionString = "Data Source = YOUCANSEEONSQLSERVER; Initial Catalog = DATABASENAME; User Id = sa; Password = sqlpasswordifyouuse";
private void Valetin_Load(object sender, EventArgs e)
{
OPIDCB.ResetText();
ValetCB.ResetText();
SqlConnection sqlconn = new SqlConnection(pr.connectionString);
SqlCommand sqlselect1 = new SqlCommand("Select EmpID, EmpName from Employees.Employee where IDPosition = 'OP'", sqlconn);
sqlconn.Open();
SqlDataReader dr1 = sqlselect1.ExecuteReader();
while (dr1.Read())
{
ArrayList MyAL = new ArrayList();
ArrayList MyAL2 = new ArrayList();
MyAL.Add(dr1.GetString(0));
MyAL2.Add(dr1.GetString(1));
foreach (string s in MyAL)
foreach (string s2 in MyAL2)
{
OPIDCB.Items.Add(s + " " + s2);
}
OPIDCB.SelectedIndex = 0;
}
dr1.Close();
sqlconn.Close();
}
If you are confusing with that code, you can visit this link: What is the right way to populate a DropDownList from a database?
Hope this help.
You can create connection string in web.config and get this param to bind in dropdownlist
Try to this link :
http://www.c-sharpcorner.com/UploadFile/rohatash/binding-dropdownlist-with-database-and-display-data-in-gridv/

Update sql database using dataset

I need some help to complete this. I have searched and tried several ways but is not enetring in my head yet. It is not homework! I am a self learner.
I managed to populate a grid selecting the table from a dropdown:
private void radDropDownList1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
if (radDropDownList1.SelectedIndex > 0)
{
radGridView1.Visible = true;
label8.Text = radDropDownList1.SelectedValue.ToString();
DataTable dt = new DataTable();
var selectedTable = radDropDownList1.SelectedValue; //Pass in the table name
string query = #"SELECT * FROM " + selectedTable;
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
radGridView1.DataSource = dt;
}
Now I am trying to write the event to update the sql table using the grid as datasource:
private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
{
DataTable dt = (DataTable)radGridView1.DataSource;
DataSet ds = new DataSet();
ds.Tables[0] = dt;
try
{
//**I am lost here!**
}
catch
{
}
}
Could you please help? How can I now update the sql table?
I don't really like the way you are managing the updates but... this code here will send an update statement:
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("UPDATE YourTable SET Column = #Parm1 WHERE Col = #Parm2", cn);
var parm1 = cmd.CreateParameter("Parm1");
parm1.Value = "SomeValue";
var parm2 = cmd.CreateParameter("Parm2");
parm2.Value = "SomeOtherValue";
cmd.Parameters.Add(parm1);
cmd.Parameters.Add(parm2);
int rowsAffected = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}

Querying MS Access from C#

I'm new in C#. I'm trying to query an *.accdb database, but having 0 row in response and datagrid stays clear. Query works from MS Access. What's wrong?
Main form class
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
OleDbConnection database;
public Form1()
{
InitializeComponent();
}
private void filterButton_Click(object sender, EventArgs e)
{
MessageBox.Show(nameFilter.Text);
InitializeComponent();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\qwe.accdb;";
try
{
database = new OleDbConnection(connectionString);
database.Open();
string queryString = "SELECT id FROM table1";
loadDataGrid(queryString);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
public void loadDataGrid(string sqlQueryString) {
OleDbCommand comm = new OleDbCommand();
comm.CommandText = sqlQueryString;
comm.CommandType = CommandType.Text;
comm.Connection = database;
Int32 returnValue = comm.ExecuteNonQuery();
MessageBox.Show(returnValue.ToString());
OleDbCommand SQLQuery = new OleDbCommand();
DataTable data = null;
dataGridView1.DataSource = null;
SQLQuery.Connection = null;
OleDbDataAdapter dataAdapter = null;
dataGridView1.Columns.Clear(); // <-- clear columns
SQLQuery.CommandText = sqlQueryString;
SQLQuery.Connection = database;
data = new DataTable();
dataAdapter = new OleDbDataAdapter(SQLQuery);
dataAdapter.Fill(data);
dataGridView1.DataSource = data;
MessageBox.Show(data.ToString());
dataGridView1.AllowUserToAddRows = false; // <-- remove the null line
dataGridView1.ReadOnly = true; // <-- so the user cannot type
}
}
}
Why not something along the lines of:
private void filterButton_Click(object sender, EventArgs e)
{
dataGridView1.Columns.Clear();
MessageBox.Show(nameFilter.Text);
InitializeComponent();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\qwe.accdb;";
try
{
using (DataTable dt = new DataTable())
{
using (OleDbDataAdapter da = new OleDbDataAdapter(new SqlCommand("SELECT id FROM table1",new OleDbConnection(connectionString))))
{
da.Fill(dt);
MessageBox.Show(dt.Rows.Count.ToString());
dataGridView1.DataSource = dt;
dataGridView1.Update();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}

SqlDataAdapter.Update or SqlCommandBuilder not working

I have a form with a datagrid, which is populated wih data from a sqlserver database. The datagrid populates fine but I am having trouble posting back the changes made by the user, to the table in the sql database. My forms code is as follows:
public partial class frmTimesheet : Form
{
private DataTable tableTS = new DataTable();
private SqlDataAdapter adapter = new SqlDataAdapter();
private int currentTSID = 0;
public frmTimesheet()
{
InitializeComponent();
}
private void frmTimesheet_Load(object sender, EventArgs e)
{
string strUser = cUser.currentUser;
cMyDate cD = new cMyDate(DateTime.Now.ToString());
DateTime date = cD.GetDate();
txtDate.Text = date.ToString();
cboTSUser.DataSource = cUser.GetListOfUsers("active");
cboTSUser.DisplayMember = "UserID";
cboTSUser.Text = strUser;
CheckForTimeSheet();
PopulateTimeSheet();
}
private void CheckForTimeSheet()
{
string strUser = cboTSUser.Text;
cMyDate cD = new cMyDate(txtDate.Text);
DateTime date = cD.GetDate();
int newTSID = cTimesheet.TimeSheetExists(strUser, date);
if (newTSID != this.currentTSID)
{
tableTS.Clear();
if (newTSID == 0)
{
MessageBox.Show("Create TimeSheet");
}
else
{
this.currentTSID = newTSID;
}
}
}
private void PopulateTimeSheet()
{
try
{
string sqlText = "SELECT EntryID, CaseNo, ChargeCode, StartTime, FinishTime, Units " +
"FROM tblTimesheetEntries " +
"WHERE TSID = " + this.currentTSID + ";";
SqlConnection linkToDB = new SqlConnection(cConnectionString.BuildConnectionString());
SqlCommand sqlCom = new SqlCommand(sqlText, linkToDB);
SqlDataAdapter adapter = new SqlDataAdapter(sqlCom);
adapter.SelectCommand = sqlCom;
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Fill(tableTS);
dataTimesheet.DataSource = tableTS;
}
catch (Exception eX)
{
string eM = "Error Populating Timesheet";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
private void txtDate_Leave(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void cboTSUser_DropDownClosed(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void dataTimesheet_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
adapter.Update(tableTS);
}
catch (Exception eX)
{
string eM = "Error on frmTimesheet, dataTimesheet_CellValueChanged";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
}
No exception occurs, and when I step through the issue seems to be with the SqlCommandBuilder which does NOT build the INSERT / UPDATE / DELETE commands based on my gien SELECT command.
Can anyone see what I am doing wrong?
What am I missing?
You need to set the UpdateCommand instead of SelectCommand on update:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The question is old, but the provided answer by#Anurag Ranjhan need to be corrected.
You need not to write the line:
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
and enough to write:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
//remove the next line
//adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The Sql update/insert/delete commands are auto generated based on this line
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
You can find the generated update sql by executing the line:
sqlBld.GetUpdateCommand().CommandText;
See the example How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual C# .NET
The problem said by OP can be checked by reviewing the Sql Statement sent by the client in SQl Server Profiler.

Categories