Reloading live charts chart only adds new data - c#

I'm using Live Charts in my application for a pareto chart. I have made a SeriesCollection. I'm loading it from a Stored Procedure in the following way:
public void LoadChart()
{
List<DataTops> dataTops = GetTops();
ChartValues<int> Pareto = new ChartValues<int>();
List<string> timevalues = new List<string>();
int selected = ComboSelect();
IDLables = new List<string>();
foreach (var item in dataTops)
{
values.Add(item.Total);
Pareto.Add(item.Running);
IDLables.Add((item.W) + "." + (item.B));
}
TopAlarms = new SeriesCollection
{
new ColumnSeries
{
Title = "Total",
Values =values,
DataLabels = false,
ScalesYAt = 0,
},
new LineSeries
{
Title = "%",
Values = Pareto,
ScalesYAt = 1,
PointGeometrySize = 0
}
};
public List<DataTops> GetTops()
{
int selected = ComboSelect();
DataSet Ds = new DataSet();
DataSetTableAdapters.TimePerID_TopTableAdapter TimerTopta = new DataSetTableAdapters.TimePerID_TopTableAdapter();
TimerTopta.Fill(Ds.TimePerID_Top, selected);
List<DataTops> Tops = new List<DataTops>();
foreach (DataRow row in Ds.Tables["TimePerID_Top"].Rows)
{
Tops.Add(new DataTops() { Total = (int)row["Total"], W = (int)row["W"], B = (int)row["B"], Amount = (int)row["Amount"], Running = (int)row["Running"] });
}
return Tops;
}
I have a combobox to select an amount to show (selected in the dataset) and a button that I use to update the chart. The Chart works fine, but whenever I press the update button it only adds new data behind the already existing data.
Live charts doesn't automatically clear the chart collection data upon loading so I did this:
private void UpdateChart_Click(object sender, RoutedEventArgs e)
{
if (TopAlarms != null)
{
TopAlarms.Clear();
}
LoadChart();
}
But it still won't clear and reload the chart. How can i reload the chart when the button is pressed so the new selected data amount will show?

after some testing and reasearch I have the following solution for clearing the chart:
try
{
if (TopAlarms != null)
{
TopAlarms.Clear();
}
}
catch { }
This is probably not the best solution but it works for me.

Related

RDLC report table not populate data from dataset

I am creating an app that prints invoices through Microsoft RDLC report.The report showing some data but the tablix is not showing the values which i provide from dataset.Please see my code below and try to solve my problem.
private void InvoiceButton_Click(object sender, EventArgs e)
{
Parameters p = new Parameters();
List<Parameters> lst = new List<Parameters>();
p.date = CurrentDateTimePicker.Text;
p.CustomerName = CustomerTextBox.Text;
if (CartDataGridView.Rows.Count != 0)
{
for (int i = 0; i < CartDataGridView.Rows.Count-1; i++)
{
lst.Add(new Parameters
{
ItemName = CartDataGridView.Rows[i].Cells[1].Value.ToString(),
Price = CartDataGridView.Rows[i].Cells[2].Value.ToString(),
Quantity = CartDataGridView.Rows[i].Cells[3].Value.ToString(),
Company = CartDataGridView.Rows[i].Cells[4].Value.ToString(),
ExpiryDate = CartDataGridView.Rows[i].Cells[5].Value.ToString(),
Total = CartDataGridView.Rows[i].Cells[7].Value.ToString()
// Subtotal = (Convert.ToInt32(CartDataGridView.Rows[i].Cells[7].Value))
});
}
}
InvoiceForm f = new InvoiceForm();
ReportDataSource rd = new ReportDataSource("MyDataSet");
rd.Value = lst;
f.reportViewer1.LocalReport.ReportEmbeddedResource = "CPMSTestPhase.InvoiceReport.rdlc";
f.reportViewer1.LocalReport.DataSources.Add(rd);
ReportParameter[] rptparam = new ReportParameter[]
{
new ReportParameter("Date",p.date),
new ReportParameter("CustomerName",p.CustomerName),
// new ReportParameter("Subtotal",p.Subtotal.ToString()),
};
f.reportViewer1.LocalReport.SetParameters(rptparam);
f.reportViewer1.RefreshReport();
f.ShowDialog();
}
}ere
I try all solutions available on youtube but did not work.
I myself figured out the issue. The issue is with the order of dataset fields and my parameters class properties. They should be the same.

Android C# Clear TextView before populating with new data

I'm trying to clear 3 TextView fields before new data is then displayed. I'm using SQLite and returning 3 phone numbers.
I can't run the app as I get "cannot convert from string to int" on the
txtFire.SetText("");
section of code.
The 3 fields in my SQLite DB are TEXT fields, so slightly confused on how to resolve this.
Any advice is appreciated.
private void EmergencyServicesData()
{
var location = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteCountry).Text;
ICursor selectData = sqliteDB.RawQuery("SELECT POLICE, FIRE, MEDICAL FROM EmergencyServices WHERE COUNTRY = '" + location + "'", new string[] { });
if (selectData.Count > 0)
{
selectData.MoveToFirst();
do
{
txtFire = (TextView)FindViewById(Resource.Id.txtFire);
txtMedical = (TextView)FindViewById(Resource.Id.txtMedical);
txtPolice = (TextView)FindViewById(Resource.Id.txtPolice);
txtFire.SetText("");
txtMedical.SetText("");
txtPolice.SetText("");
EmergencyServices emergencyServices = new EmergencyServices();
EmergencyServices.Clear();
emergencyServices.POLICE = selectData.GetString(selectData.GetColumnIndex("POLICE"));
emergencyServices.FIRE = selectData.GetString(selectData.GetColumnIndex("FIRE"));
emergencyServices.MEDICAL = selectData.GetString(selectData.GetColumnIndex("MEDICAL"));
EmergencyServices.Add(emergencyServices);
}
while (selectData.MoveToNext());
selectData.Close();
}
foreach (var item in EmergencyServices)
{
LayoutInflater layoutInflater = (LayoutInflater)BaseContext.GetSystemService(Context.LayoutInflaterService);
View addView = layoutInflater.Inflate(Resource.Layout.EmergencyServices, null);
TextView txtPoliceData = addView.FindViewById<TextView>(Resource.Id.txtPolice);
TextView txtFireData = addView.FindViewById<TextView>(Resource.Id.txtFire);
TextView txtMedicalData = addView.FindViewById<TextView>(Resource.Id.txtMedical);
txtPoliceData.Text = item.POLICE;
txtFireData.Text = item.FIRE;
txtMedicalData.Text = item.MEDICAL;
container.AddView(addView);
}
}
You have nullpointers in your textviews. Change to this.
LayoutInflater layoutInflater = (LayoutInflater)BaseContext.GetSystemService(Context.LayoutInflaterService);
View addView = layoutInflater.Inflate(Resource.Layout.EmergencyServices, null);
txtFire = addView.FindViewById<TextView>(Resource.Id.txtFire);
txtMedical = addView.FindViewById<TextView>(Resource.Id.txtMedical);
txtPolice = addView.FindViewById<TextView>(Resource.Id.txtPolice);

Get Data from SQLite into ArrayAdapter / ListView - Android C# Xamarin

I am trying to get the data from my SQLite table into a List<string> and then into an ArrayAdapter<string> and into a ListView.
How would I get the data pulled from the below code, into a ListView using an ArrayAdapter?
DB Helper.cs:
public List<string> getNoteList()
{
List<string> noteList = new List<string>();
SQLiteDatabase db = this.ReadableDatabase;
ICursor cursor = db.Query(DB_TABLE, new string[] { DB_COLUMN}, null, null, null, null, null);
while (cursor.MoveToNext())
{
int index = cursor.GetColumnIndex(DB_COLUMN);
noteList.Add(cursor.GetString(index));
}
return noteList;
}
As you can see it is put into noteList, but how would I code an array adapter so that the noteList goes into a ListView?
UPDATE 1: MainActivity.cs
public void LoadNoteList()
{
List<string> noteList = dbHelper.getNoteList();
adapter = new ArrayAdapter<string>(this, Resource.Layout.list_black_text, noteList);
lvNotes.Adapter = adapter;
}
Error:
Change noteList's type to ArrayList and add follow line at the place after your ListView being initialization
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, noteList);
listview.setAdapter(adapter);
try this
here cards is my linked-list
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice);
for (MerchantCard card : cards) {
arrayAdapter.add(card.getName());
}
ListView listView = (ListView) mView.findViewById(R.id.listView);
listView.setAdapter(arrayAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedCardTypeId = cards.get(position).getId();
Log.d("request", cards.get(position).getId() + " " + cards.get(position).getName());
}
});

Checkbox turning multiple values true

I've been stuck of this for a while and would love some insight.
When I add a new user or source and check the drawn checkbox, it causes the bool to be true when checked, as expected.
However it also checks all the other users connected to that source as true or false.
[before]
[after]
This only occurs when I load the XML file into my program that already had existing data, then add new Users or Sources via the UI.
this is a part of the LoadXML Method.
// Load the source list
sourceProps.SystemSources.Clear();
fCMUserSourceBindingSource.Clear();
fCMSourceBindingSource.Clear();
foreach (FusionSource src in fusionSystem.sourceList)
{
FCMSource fSource = new FCMSource(src);
sourceProps.SystemSources.Add(fSource);
fCMSourceBindingSource.Add(fSource);
fCMUserSourceBindingSource.Add(fSource);
}
txtSourceID.Text = sourceProps.GenerateNextSourceId();
// Load the user data from the fusionSystem object.
userProfile.SystemUserList.Clear();
//currently clears grid. might need to clear list instead
fCMUserBindingSource.Clear();
foreach (FusionUser usr in fusionSystem.userList)
{
FCMUser fUser = new FCMUser(usr);
userProfile.SystemUserList.Add(fUser);
fCMUserBindingSource.Add(fUser);
foreach (FusionSourcePermission srcPerm in usr.SourcePermissionList)
{
FCMSource fSource = new FCMSource(srcPerm);
fUser.fusionUserSources.Add(fSource);
}
}
AddColumnsUsersToSourceAllocation();
txtUserID.Text = userProfile.GenerateNextUserId();
// Load the zone group data from the fusionSystem object
zoneProps.systemZoneGroupList.Clear();
fCMZoneGroupBindingSource.Clear();
Any help would be appreciated.
Edit
The ListView is not binded and all the 'checking' is done programmatically when the user activates the click event.
private void lstSourceToUser_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
if (e.ColumnIndex > 1)
{
int usrIndex = userProfile.GetUserIndexByID(e.Header.Name);
int srcIndex = userProfile.GetUsersSourceIndex(e.Header.Name, e.Item.SubItems[0].Text);
Graphics g = e.Graphics;
CheckBoxRenderer.DrawCheckBox(g,new Point((e.Bounds.X + e.Bounds.Width/2 -10 ),(e.Bounds.Y)), userProfile.SystemUserList[usrIndex].fusionUserSources[srcIndex].UserSourceChkBox.MyCheckedState ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal);
}
else
// Draw the other subitems with default drawing.
e.DrawDefault = true;
}
Edit
This is the FCMSource constructor.
public FCMSource(string sourceId, string sourceName, string icnId, string lstIndx)
{
id = sourceId;
icon = icnId;
name = sourceName;
listIndex = lstIndx;
UserSourceCheckState = false;
UserSourceChkBox = new MyCheckBoxItem(false);
}
public FCMSource(FCMSource fSource, bool chk)
{
name = fSource.name;
icon = fSource.icon;
id = fSource.id;
listIndex = fSource.listIndex;
UserSourceCheckState = chk ? true : false;
UserSourceChkBox = new MyCheckBoxItem(chk);
}
And this is the FCMUser constructor which contains the different Sources.
public FCMUser(string userid, string nm, string icn, string pinNo, CheckBox pinEn, string lstIndx)
{
id = userid;
name = nm;
icon = icn;
pin = pinNo;
pinEnabled = pinEn.CheckState;
chkBoxPINEnable = new MyCheckBoxItem(false);
fusionUserSources = new List<FCMSource>();
ListIndex = lstIndx;
updateCheckbox();
}

Dynamically created LinkButton won't go into command event

I've asked this before, but sadly I'm still having issues and the issue wasn't resolved. Basically, I'm dynamically creating a LinkButton for each row of a table I am generating, and that button has the task of deleting the row with the corresponding ID from the database. To do this, I seemingly need to assign the LinkButton a Command so it'll go into the event when it is clicked. Problem is, when the button's clicked the program never goes into the command - I've put breakpoints in there and it never goes into them. Here's my code:
protected void Page_Init(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
ColorConverter conv = new ColorConverter();
string connection = ConfigurationManager.ConnectionStrings["TPRTestConnectionString"].ConnectionString;
TPRDBDataContext dc = new TPRDBDataContext();
DataContext db = new DataContext(connection);
Table<SageAccount> SageAccount = db.GetTable<SageAccount>();
Table<InvoiceItem> InvoiceItem = db.GetTable<InvoiceItem>();
Table<Invoice> Invoice = db.GetTable<Invoice>();
Boolean alloweditting = (from s in dc.Invoices where s.id.ToString() == Request.QueryString["id"] select s.alloweditting).Single();
if (alloweditting == false)
{
dtlsInsert.Visible = false;
modalPanel.Visible = false;
}
int sagepk = (from s in dc.Invoices where s.id.ToString() == Request.QueryString["id"] select s.sageaccount).Single();
lblSageID.Text = (from s in dc.SageAccounts where s.ID == sagepk select s.SageID).Single();
lblDate.Text = DateTime.Now.ToShortDateString();
Table table = new Table();
table.Width = Unit.Percentage(100);
table.GridLines = (GridLines)3;
TableHeaderRow header = new TableHeaderRow();
header.BackColor = (System.Drawing.Color)conv.ConvertFromString("#EDEDED");
foreach (string header2 in new string[] { "", "Quantity", "Rate", "Description", "Nominal Code", "Subtotal" })
{
TableCell cell = new TableCell();
cell.Text = header2;
header.Cells.Add(cell);
}
table.Rows.Add(header);
var data = (from s in dc.InvoiceItems where s.invoiceid.ToString() == Request.QueryString["id"].ToString() select s);
foreach (var x in data)
{
TableRow row = new TableRow();
if (x.invoicetext == null)
{
decimal total;
try
{
total = (decimal)x.rate * (decimal)x.quantity;
}
catch
{
total = 0;
}
int i = 0;
foreach (string columnData in new string[] { x.id.ToString(), x.quantity.ToString(), x.rate.ToString(), x.description, x.nominalcode, total.ToString("N2") })
{
TableCell cell = new TableCell();
{
if (i == 0)
{
LinkButton lnkdel = new LinkButton();
lnkdel.Text = "Delete";
lnkdel.ID = "lnkDel" + Guid.NewGuid();
if (alloweditting == false)
{
lnkdel.Enabled = false;
}
lnkdel.Font.Bold = false;
lnkdel.CommandArgument = x.id.ToString();
//lnkdel.Command += lnkdel_Command;
//lnkdel.Command += new CommandEventHandler(this.lnkdel);
cell.Controls.Add(lnkdel);
i++;
}
else
{
cell.Text = columnData;
}
}
row.Cells.Add(cell);
}
runningtotal = runningtotal + total;
}
else
{
int i = 0;
foreach (string columnData in new string[] { x.id.ToString(), x.invoicetext })
{
TableCell cell = new TableCell();
if (i == 0)
{
LinkButton lnkdel = new LinkButton();
lnkdel.Text = "Delete";
lnkdel.ID = "lnkDel" + Guid.NewGuid();
if (alloweditting == false)
{
lnkdel.Enabled = false;
}
lnkdel.Font.Bold = false;
//lnkdel.Command += lnkdel_Command;
//lnkdel.Command += new CommandEventHandler(this.lnkdel);
lnkdel.CommandArgument = x.id.ToString();
cell.Controls.Add(lnkdel);
i++;
}
else
{
cell.Text = columnData;
cell.ColumnSpan = 5;
}
row.Cells.Add(cell);
}
}
switch (x.formatoptions)
{
case 1:
row.ForeColor = (System.Drawing.Color)conv.ConvertFromString("black");
row.Font.Bold = false;
break;
case 2:
row.ForeColor = (System.Drawing.Color)conv.ConvertFromString("black");
row.Font.Bold = true;
break;
case 3:
row.ForeColor = (System.Drawing.Color)conv.ConvertFromString("red");
row.Font.Bold = false;
break;
case 4:
row.ForeColor = (System.Drawing.Color)conv.ConvertFromString("red");
row.Font.Bold = true;
break;
}
table.Rows.Add(row);
}
TableFooterRow row2 = new TableFooterRow();
TableCell cell2 = new TableCell();
cell2.Text = "<span style\"text-align: right; width: 100%;\">Total = <b>" + runningtotal.ToString("N2") + "</b></span>";
cell2.ColumnSpan = 6;
row2.Cells.Add(cell2);
table.Rows.Add(row2);
var update = (from s in dc.Invoices where s.id.ToString() == Request.QueryString["id"] select s).Single();
update.total = runningtotal;
dc.SubmitChanges();
datatable.Controls.Clear();
datatable.Controls.Add(table);
}
else
{
Response.Redirect("Invoices.aspx");
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void lnkdel_Command(object sender, CommandEventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["TPRTestConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
SqlCommand comm = new SqlCommand("DELETE FROM InvoiceItem WHERE id = #id", conn);
comm.Parameters.AddWithValue("#id", e.CommandArgument.ToString());
conn.Open();
try
{
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
Note I've commented out 2 of the crucial lines for posting here, just to point out that I've tried both of the lines that's commented out, and neither work :(
You need to add the controls on every postback. You appear to be only creating them on the initial get (that query string check). On the post back, those controls never get recreated so no event fires.
It's notoriously counter-intuitive, but while ASP.NET bends over backwards to make you think that the instance of your page class is the same between two HTTP requests, the reality is that they are not the same. A new instance is created each time. It looks like you are trying to avoid adding the dynamically generated controls multiple times -- thinking you don't want duplicates. The reality is that you will never get duplicates when adding dynamically generated controls in a life-cycle method such as OnInit() since it's always a new instance of the page class, and thus those dynamically generated controls are gone.
The reason this is usually transparent to developers is that all the controls in the code-front are automatically re-generated for you on both the initial request and every single post-back. For your dynamically created controls, you happen to have this line:
if (Request.QueryString["id"] != null) { ... }
Unless you're doing something special, that "id" attribute will not be in the query string on the postback. This means that none of the code in the if block will be run on the post back (when your event actually fires.) This means that your if-check at the top should be removed altogether. All that code should run for each and every request (GET and POST).
Just saying I've created a workaround - simply creating a simple link to the page, along with a query string containing the id of the row to delete

Categories