Object not shown on Canvas (WPF Application) - c#

In this Application, i have a car class with a method called Spawn (which should draw the object on a Canvas which i defined in the XAML file). I call the Method in MainWindow, but when I run my program, there is no car being drawn onto the Canvas.
Here is the Spawn method:
public void Spawn(Canvas cvs)
{
cvs = new Canvas();
cvs.Children.Clear();
carBody.Width = 70;
carBody.Height = 120;
carBody.Background = new SolidColorBrush(Color);
Canvas.SetLeft(carBody, SpawnLocation.X);
Canvas.SetTop(carBody, SpawnLocation.Y);
Rectangle[] tires = new Rectangle[4];
Rectangle[] windows = new Rectangle[2];
Label lblBrand = new Label();
RotateTransform rotation = new RotateTransform();
// Reifen
tires[0] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[0], -9);
Canvas.SetTop(tires[0], 18);
tires[1] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[1], 61);
Canvas.SetTop(tires[1], 18);
tires[2] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[2], -9);
Canvas.SetTop(tires[2], 80);
tires[3] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[3], 61);
Canvas.SetTop(tires[3], 80);
// Fenster
windows[0] = new Rectangle() // Front
{
Fill = Brushes.White,
Width = 50,
Height = 40
};
Canvas.SetLeft(windows[0], 0);
Canvas.SetTop(windows[0], 0);
windows[1] = new Rectangle() // rear
{
Fill = Brushes.White,
Width = 50,
Height = 50
};
Canvas.SetLeft(windows[1], 0);
Canvas.SetTop(windows[1], 0);
// Label Automarke
lblBrand.Width = 40;
lblBrand.Height = 23;
lblBrand.Content = Brand;
// Add2Canvas
for (int i = 0; i < tires.Length; i++)
carBody.Children.Add(tires[i]);
for (int i = 0; i < windows.Length; i++)
carBody.Children.Add(windows[i]);
carBody.Children.Add(lblBrand);
if (Direction == "nord")
{
rotation.Angle = 0;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
else if (Direction == "süd")
{
rotation.Angle = 180;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
else if (Direction == "west")
{
rotation.Angle = 90;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
else if (Direction == "ost")
{
rotation.Angle = 270;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
cvs.Children.Add(carBody);
}
Calling the methodMainWindow:
Car car1;
public MainWindow()
{
InitializeComponent();
car1 = new Car("Audi", Colors.Red);
car1.Direction = "west";
car1.SpawnLocation = new Point(550, 340);
car1.Spawn(gameScreen);
}
Thanks in advance!

Fixed it! I initialized the argmument of my Spawn method, it now works after I deleted it.
My method looked like this first:
public void Spawn(Canvas cvs)
{
cvs = new Canvas();
cvs.Children.Clear();
carBody.Width = 70;
I initialized my the Argument, but since i don't wanna create a new Canvas, i deleted these two first lines of my method.
public void Spawn(Canvas cvs)
{
carBody.Width = 70;
carBody.Height = 120;
carBody.Background = new SolidColorBrush(Color);
Now its working fine.

Related

How to print C# chart with more pages

I have C# project already done but im having issue with printing it's charts when comes out with more pages of data points, i got the scroll bar work when start getting more pages so the user can review all data on all pages but i could not find how to make the print preview shows them or print them,
when click on print, it shows only the first page on the print preview and same thing when print it out.
her is the print code:
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document = this.chart1.Printing.PrintDocument;
((Form)ppd).WindowState = FormWindowState.Maximized;
chart1.Printing.PrintDocument.DefaultPageSettings.Landscape = true;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Left = 0;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Right = 0;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Top = 0;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Bottom = 0;
ppd.ShowDialog();
and here is the chart load code:
public void loadChart(string sqlvalue)//load chart method
{
chart1.ChartAreas[0].AxisY.Maximum = 55;
chart1.ChartAreas[0].AxisY.Minimum = 35;
chart1.ChartAreas[0].AxisY.Interval = 5;//control how many lines/Interval
chart1.ChartAreas[0].AxisY.ScrollBar.Enabled = true;
chart1.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
chart1.ChartAreas[0].AxisX.Minimum = 0;
// chart1.ChartAreas[0].AxisX.Maximum = 10;
chart1.ChartAreas[0].AxisX.Interval = 1;
//X AXES label angle
chart1.ChartAreas[0].AxisX.LabelStyle.Angle = 60;
da = new SqlDataAdapter(sqlvalue, cn.connect());
da.Fill(dt);
this.chart1.DataSource = dt;
this.chart1.Series["left"].XValueMember = dt.Columns[3].ToString();//date data
this.chart1.Series["left"].YValueMembers = dt.Columns[1].ToString();//spindle 1 data
this.chart1.Series["Right"].YValueMembers = dt.Columns[2].ToString();//spindle 2 data
//label the series lines, Backcolor and forcolor
chart1.Series[0].LabelBackColor = Color.Red;
chart1.Series[0].LabelForeColor = Color.White;
//datapoint marker's color, bordercolor,style and size
chart1.Series[0].MarkerColor = Color.White;
chart1.Series[0].MarkerBorderColor = Color.Black;
chart1.Series[0].MarkerStyle = MarkerStyle.Circle;
chart1.Series[0].MarkerSize = 8;
//datapoint marker's color, style and size
chart1.Series[1].MarkerColor = Color.White;
chart1.Series[1].MarkerBorderColor = Color.Black;
chart1.Series[1].MarkerStyle = MarkerStyle.Circle;
chart1.Series[1].MarkerSize = 8;
chart1.Series[1].LabelBackColor = Color.Blue;
chart1.Series[1].LabelForeColor = Color.White;
//Chart background lines color
chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.Silver;
chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.Silver;
this.chart1.DataBind();
cn.disconnect();
// enable autoscroll
chart1.ChartAreas[0].CursorX.AutoScroll = true;//------------
chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
chart1.ChartAreas[0].AxisX.ScaleView.Zoom(0, 15);
chart1.ChartAreas[0].AxisX.ScrollBar.ButtonStyle = ScrollBarButtonStyles.SmallScroll;
// set scrollbar small change to the target size
chart1.ChartAreas[0].AxisX.ScaleView.SmallScrollSize = 15;
Legend left = new Legend();
Legend LC = CustomCloneLegend(chart1, left);
chart1.Legends.Add(LC);
chart1.Padding = Padding.Empty;
ChartArea CA = chart1.ChartAreas[0];
CA.Position = new ElementPosition(4,6, 100, 90);
}
Thank you for your time and help, here is the chart code update:
private static Image MergeImages(List<Image> imageList)
{
var finalSize = new Size();
foreach (var image in imageList)
{
if (image.Width > finalSize.Width)
{
finalSize.Width = image.Width;
}
finalSize.Height += image.Height;
}
var outputImage = new Bitmap(finalSize.Width, finalSize.Height);
using (var gfx = Graphics.FromImage(outputImage))
{
var y = 0;
foreach (var image in imageList)
{
gfx.DrawImage(image, 0, y);
y += image.Height;
}
}
return outputImage;
}
The second method:
List<Image> ChartsToImages(List<Chart> charts)
{
var imageList = new List<Image>();
foreach (var c in charts)
{
using (var ms = new MemoryStream())
{
c.SaveImage(ms, ChartImageFormat.Png);
var bmp = System.Drawing.Bitmap.FromStream(ms);
imageList.Add(bmp);
}
}
return imageList;
}
and this code
var chartList = new List<Chart> { chart1 };
var imageList = ChartsToImages(chartList);
var finalImage = MergeImages(imageList);
finalImage.Save("D:\\Junk.png", ImageFormat.Png);
Im not sure is that what you mean by your first comment, but i found this code here under Converting chart to image questions. this code convert and saves the chart in the same amount of pages but i need to show them in the printpreviewcontrol and print them.
Below code refers to the as per page count starting point and ending point based printing. And Grid view value chars are row loop based counting the page.
private int numberOfItemsPerPage = 0;
private int numberOfItemsPrintedSoFar = 0;
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int height = 480; //page height stating point
for (int l = numberOfItemsPrintedSoFar; l < dataGridView2.Rows.Count; l++)
{
numberOfItemsPerPage = numberOfItemsPerPage + 1;
if (numberOfItemsPerPage <= 25) // 25 is Page Line Item
{
numberOfItemsPrintedSoFar++;
if (numberOfItemsPrintedSoFar <= dataGridView2.Rows.Count)
{
height += dataGridView2.Rows[0].Height;
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[0].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(5, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[1].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(170, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[2].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(290, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[3].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(345, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
}
else
{
e.HasMorePages = false;
}
}
else
{
numberOfItemsPerPage = 0;
e.HasMorePages = true;
return;
}
}
numberOfItemsPerPage = 0;
numberOfItemsPrintedSoFar = 0;
}

i need audio frequency response graph c#

i need logarithm x-axis based linechart for audio frequency magnitude response for c# winform , i have tested default chart and livechart but c'ant align x axis attached photo like . anybody know please help me.
sorry for my bad english
Live Chart Code :
cartesianChart1.AxisY.Add(new Axis
{
Title = "Gain",
MaxValue = 10,
MinValue = -15,
Separator = new Separator
{
Stroke = new SolidColorBrush(System.Windows.Media.Color.FromRgb(46, 35, 35))
}
});
cartesianChart1.AxisX.Add(new LogarithmicAxis
{
Title = "Freq",
LabelFormatter = (value) => (Math.Pow(10, value).ToString("N0")+"Hz"),
Base = 10,
Separator = new Separator
{
Step=0,
Stroke = new SolidColorBrush(System.Windows.Media.Color.FromRgb(35, 35, 35))
},
});
cartesianChart1.BackColor = System.Drawing.Color.FromArgb(0, 0, 0);
cartesianChart1.DisableAnimations = true;
cartesianChart1.Hoverable = false;
cartesianChart1.DataTooltip = null;
var Datapoint = new ChartValues<ObservablePoint>{
new ObservablePoint(1, 5),
new ObservablePoint(5, -4),
new ObservablePoint(10, 6),
new ObservablePoint(100, 4),
new ObservablePoint(150, 7),
new ObservablePoint(1000, 2),
new ObservablePoint(10000, 8),
new ObservablePoint(15000, 2),
new ObservablePoint(20000, -7),
};
cartesianChart1.Series = new SeriesCollection(Mappers.Xy<ObservablePoint>()
.X(point => Math.Log10(point.X))
.Y(point => point.Y))
{
new LineSeries
{
PointGeometry = null,
PointGeometrySize = 0,
Values = Datapoint,
}
};
Live Chart Display :
Default Chart Code :
var r = new Random();
float val;
var chart = chart1.ChartAreas[0];
chart.AxisX.IntervalType = DateTimeIntervalType.Number;
chart.AxisX.LabelStyle.Format = "";
chart.AxisY.LabelStyle.Format = "";
chart.AxisY.LabelStyle.IsEndLabelVisible = true;
chart.AxisX.Minimum = 0;
chart.AxisX.Maximum = 20000;
chart.AxisY.Minimum = -15;
chart.AxisY.Maximum = 10;
chart.AxisX.Interval = 500;
chart.AxisY.Interval = 3;
chart.BackColor = Color.Black;
chart1.Series.Add("Sakthi");
chart1.Series["Sakthi"].ChartType = SeriesChartType.Spline;
chart1.Series["Sakthi"].Color = Color.Yellow;
chart1.Series["Sakthi"].BorderWidth = 3;
chart1.Series["Sakthi"].BorderColor = Color.Black;
chart1.ChartAreas[0].AxisX.MajorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.FromArgb(35, 35, 35);
chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.FromArgb(35, 35, 35);
chart1.ChartAreas[0].AxisY.LabelStyle.ForeColor = Color.White;
chart1.ChartAreas[0].AxisX.LabelStyle.ForeColor = Color.White;
chart1.Legends[0].Enabled = false;
chart.AxisY.StripLines.Add(new StripLine
{
BorderDashStyle = ChartDashStyle.Dot,
BorderColor = Color.White,
StripWidth = 0
});
chart1.Series.Clear();
chart1.Series.Add("Sakthi");
chart1.Series["Sakthi"].ChartType = SeriesChartType.Spline;
chart1.Series["Sakthi"].Color = Color.Yellow;
chart1.Series["Sakthi"].BorderWidth = 3;
chart1.Series["Sakthi"].BorderColor = Color.Black;
for (int i = 0; i < 10; i++)
{
val = r.Next(-15, 10);
chart1.Series["Sakthi"].Points.AddXY(i*2000, val);
}
Default Chart Display :
i want this this type x axis label :

Print all data in the DataGrid in WPF

I am working on WPF application. I have data in the DataGrid which I have to print all the data present in it. I tried like this...
publicMainWindow()
{
InitializeComponent();
DataTabledt = newDataTable();
dt.Columns.Add("S.No");
dt.Columns.Add("Name");
dt.Columns.Add("Father's Name");
dt.Columns.Add("D-O-B");
dt.Columns.Add("Qualification");
dt.Columns.Add("Gender");
dt.Columns.Add("SSC %");
dt.Columns.Add("+2 %");
dt.Columns.Add("Graduation %");
dt.Columns.Add("Work Experience");
dt.Columns.Add("Company");
object[] rowValues = {"01","Gopi","Ravi","31","Degree","M", "88","85", "80","2 Years","Blah Blah"};
dt.Rows.Add(rowValues);
dt.AcceptChanges();
myGrid.DataContext = dt.DefaultView;
}
privatevoidPrint_Click(object sender, RoutedEventArgs e)
{
PrintDialogprintDlg = newPrintDialog();
if ((bool)printDlg.ShowDialog().GetValueOrDefault())
{
Sizepagesize = newSize(printDlg.PrintableAreaWidth,printDlg.PrintableAreaHeight);
myGrid.Measure(pagesize);
myGrid.Arrange(newRect(5, 5, pagesize.Width, pagesize.Height));
printDlg.PrintVisual(myGrid, "Personal Information");
}
}
when I click on print button it is printing only the data which we can see as below
But in my case it is not printing work experience and company columns. How can I Print all the fields. Please help me out
EDIT: I think FlowDocument is used, but suppose I have 50 rows I cannot use FlowDocument. How can I Print in this case.
I have done code recently. It is tested code.It will print every datagrid with all records.It is easy and simple code.You would add a class. If you want to decorate a datagrid then go to PrintDG class then decorate it according to your own requirement.
Follow these steps.
Step1: Add these references on top.
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
public class PrintDG
{
public void printDG(DataGrid dataGrid, string title)
{
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
FlowDocument fd = new FlowDocument();
Paragraph p = new Paragraph(new Run(title));
p.FontStyle = dataGrid.FontStyle;
p.FontFamily = dataGrid.FontFamily;
p.FontSize = 18;
fd.Blocks.Add(p);
Table table = new Table();
TableRowGroup tableRowGroup = new TableRowGroup();
TableRow r = new TableRow();
fd.PageWidth = printDialog.PrintableAreaWidth;
fd.PageHeight = printDialog.PrintableAreaHeight;
fd.BringIntoView();
fd.TextAlignment = TextAlignment.Center;
fd.ColumnWidth = 500;
table.CellSpacing = 0;
var headerList = dataGrid.Columns.Select(e => e.Header.ToString()).ToList();
List<dynamic> bindList = new List<dynamic>();
for (int j = 0; j < headerList.Count; j++)
{
r.Cells.Add(new TableCell(new Paragraph(new Run(headerList[j]))));
r.Cells[j].ColumnSpan = 4;
r.Cells[j].Padding = new Thickness(4);
r.Cells[j].BorderBrush = Brushes.Black;
r.Cells[j].FontWeight = FontWeights.Bold;
r.Cells[j].Background = Brushes.DarkGray;
r.Cells[j].Foreground = Brushes.White;
r.Cells[j].BorderThickness = new Thickness(1, 1, 1, 1);
var binding = (dataGrid.Columns[j] as DataGridBoundColumn).Binding as Binding;
bindList.Add(binding.Path.Path);
}
tableRowGroup.Rows.Add(r);
table.RowGroups.Add(tableRowGroup);
for (int i = 0; i < dataGrid.Items.Count; i++)
{
dynamic row;
if (dataGrid.ItemsSource.ToString().ToLower() == "system.data.linqdataview")
{ row = (DataRowView)dataGrid.Items.GetItemAt(i); }
else
{
row = (BalanceClient)dataGrid.Items.GetItemAt(i);
}
table.BorderBrush = Brushes.Gray;
table.BorderThickness = new Thickness(1, 1, 0, 0);
table.FontStyle = dataGrid.FontStyle;
table.FontFamily = dataGrid.FontFamily;
table.FontSize = 13;
tableRowGroup = new TableRowGroup();
r = new TableRow();
for (int j = 0; j < row.Row.ItemArray.Count(); j++)
{
if (dataGrid.ItemsSource.ToString().ToLower() == "system.data.linqdataview")
{
r.Cells.Add(new TableCell(new Paragraph(new Run(row.Row.ItemArray[j].ToString()))));
}
else
{
r.Cells.Add(new TableCell(new Paragraph(new Run(row.GetType().GetProperty(bindList[j]).GetValue(row, null)))));
}
r.Cells[j].ColumnSpan = 4;
r.Cells[j].Padding = new Thickness(4);
r.Cells[j].BorderBrush = Brushes.DarkGray;
r.Cells[j].BorderThickness = new Thickness(0, 0, 1, 1);
}
tableRowGroup.Rows.Add(r);
table.RowGroups.Add(tableRowGroup);
}
fd.Blocks.Add(table);
printDialog.PrintDocument(((IDocumentPaginatorSource)fd).DocumentPaginator, "");
}
}
}
Step2: Then go to print button click event and create object of PrintDG class then call printDG pass to It two parameters datagridname and title.
Like :
private void print_button_Click(object sender, RoutedEventArgs e)
{
PrintDG print = new PrintDG();
print.printDG(datagridName, "Title");
}
If any error occurs during execution tell me and I will solve It.This is running code only, you need copy and paste.
Edited:
I declared row as dynamic. The dynamic keyword decides at run time which type to instantiate, either DataTable or another.
I work with This :
// Author : Kadi Okba
public class WpfPrinting
{
public const double cm = 37;
public double Margin = 0.5 * cm;
public double PageWidth = 21 * cm;
public double PageHeight = 29 * cm;
public double RowHeight = 0.7 * cm;
public bool PageNumberVisibility = true;
public bool DateVisibility = true;
public double FontSize = 14;
public double HeaderFontSize = 14;
public bool IsBold = false;
public void PrintDataGrid(FrameworkElement header, DataGrid grid, FrameworkElement footer, PrintDialog printDialog)
{
if (header == null) { header = new FrameworkElement(); header.Width = 1; header.Height = 1; }
if (footer == null) { footer = new FrameworkElement(); footer.Width = 1; footer.Height = 1; }
if (grid == null) return;
Size pageSize = new Size(PageWidth, PageHeight);
FixedDocument fixedDoc = new FixedDocument();
fixedDoc.DocumentPaginator.PageSize = pageSize;
double GridActualWidth = grid.ActualWidth == 0 ? grid.Width : grid.ActualWidth;
double PageWidthWithMargin = pageSize.Width - Margin * 2;
double PageHeightWithMargin = pageSize.Height - Margin * 2;
// scale the header
double headerScale = (header?.Width ?? 0) / PageWidthWithMargin;
double headerWidth = PageWidthWithMargin;
double headerHeight = (header?.Height ?? 0) * headerScale;
header.Height = headerHeight;
header.Width = headerWidth;
// scale the footer
double footerScale = (footer?.Width ?? 0) / PageWidthWithMargin;
double footerWidth = PageWidthWithMargin;
double footerHeight = (footer?.Height ?? 0) * footerScale;
footer.Height = footerHeight;
footer.Width = footerWidth;
int pageNumber = 1;
string Now = DateTime.Now.ToShortDateString();
//add the header
FixedPage fixedPage = new FixedPage();
fixedPage.Background = Brushes.White;
fixedPage.Width = pageSize.Width;
fixedPage.Height = pageSize.Height;
FixedPage.SetTop(header, Margin);
FixedPage.SetLeft(header, Margin);
fixedPage.Children.Add(header);
// its like cursor for current page Height to start add grid rows
double CurrentPageHeight = headerHeight + 1 * cm;
int lastRowIndex = 0;
bool IsFooterAdded = false;
for (;;)
{
int AvaliableRowNumber;
var SpaceNeededForRestRows = (CurrentPageHeight + (grid.Items.Count - lastRowIndex) * RowHeight);
//To avoid printing the footer in a separate page
if (SpaceNeededForRestRows > (pageSize.Height - footerHeight - Margin) && (SpaceNeededForRestRows < (pageSize.Height - Margin)))
AvaliableRowNumber = (int)((pageSize.Height - CurrentPageHeight - Margin - footerHeight) / RowHeight);
// calc the Avaliable Row acording to CurrentPageHeight
else AvaliableRowNumber = (int)((pageSize.Height - CurrentPageHeight - Margin) / RowHeight);
// create new page except first page cause we created it prev
if (pageNumber > 1)
{
fixedPage = new FixedPage();
fixedPage.Background = Brushes.White;
fixedPage.Width = pageSize.Width;
fixedPage.Height = pageSize.Height;
}
// create new data grid with columns width and binding
DataGrid gridToAdd;
gridToAdd = GetDataGrid(grid, GridActualWidth, PageWidthWithMargin);
FixedPage.SetTop(gridToAdd, CurrentPageHeight); // top margin
FixedPage.SetLeft(gridToAdd, Margin); // left margin
// add the avaliable rows to the cuurent grid
for (int i = lastRowIndex; i < grid.Items.Count && i < AvaliableRowNumber + lastRowIndex; i++)
{
gridToAdd.Items.Add(grid.Items[i]);
}
lastRowIndex += gridToAdd.Items.Count + 1;
// add date
TextBlock dateText = new TextBlock();
if (DateVisibility) dateText.Visibility = Visibility.Visible;
else dateText.Visibility = Visibility.Hidden;
dateText.Text = Now;
// add page number
TextBlock PageNumberText = new TextBlock();
if (PageNumberVisibility) PageNumberText.Visibility = Visibility.Visible;
else PageNumberText.Visibility = Visibility.Hidden;
PageNumberText.Text = "Page : " + pageNumber;
FixedPage.SetTop(dateText, PageHeightWithMargin);
FixedPage.SetLeft(dateText, Margin);
FixedPage.SetTop(PageNumberText, PageHeightWithMargin);
FixedPage.SetLeft(PageNumberText, PageWidthWithMargin - PageNumberText.Text.Length * 10);
fixedPage.Children.Add(gridToAdd);
fixedPage.Children.Add(dateText);
fixedPage.Children.Add(PageNumberText);
// calc Current Page Height to know the rest Height of this page
CurrentPageHeight += gridToAdd.Items.Count * RowHeight;
// all grid rows added
if (lastRowIndex >= grid.Items.Count)
{
// if footer have space it will be added to the same page
if (footerHeight < (PageHeightWithMargin - CurrentPageHeight))
{
FixedPage.SetTop(footer, CurrentPageHeight + Margin);
FixedPage.SetLeft(footer, Margin);
fixedPage.Children.Add(footer);
IsFooterAdded = true;
}
}
fixedPage.Measure(pageSize);
fixedPage.Arrange(new Rect(new Point(), pageSize));
fixedPage.UpdateLayout();
PageContent pageContent = new PageContent();
((IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
pageNumber++;
// go to start position : New page Top
CurrentPageHeight = Margin;
// this mean that lastRowIndex >= grid.Items.Count and the footer dont have enough space
if (lastRowIndex >= grid.Items.Count && !IsFooterAdded)
{
FixedPage ffixedPage = new FixedPage();
ffixedPage.Background = Brushes.White;
ffixedPage.Width = pageSize.Width;
ffixedPage.Height = pageSize.Height;
FixedPage.SetTop(footer, Margin);
FixedPage.SetLeft(footer, Margin);
TextBlock fdateText = new TextBlock();
if (DateVisibility) fdateText.Visibility = Visibility.Visible;
else fdateText.Visibility = Visibility.Hidden;
dateText.Text = Now;
TextBlock fPageNumberText = new TextBlock();
if (PageNumberVisibility) fPageNumberText.Visibility = Visibility.Visible;
else fPageNumberText.Visibility = Visibility.Hidden;
fPageNumberText.Text = "Page : " + pageNumber;
FixedPage.SetTop(fdateText, PageHeightWithMargin);
FixedPage.SetLeft(fdateText, Margin);
FixedPage.SetTop(fPageNumberText, PageHeightWithMargin);
FixedPage.SetLeft(fPageNumberText, PageWidthWithMargin - PageNumberText.ActualWidth);
ffixedPage.Children.Add(footer);
ffixedPage.Children.Add(fdateText);
ffixedPage.Children.Add(fPageNumberText);
ffixedPage.Measure(pageSize);
ffixedPage.Arrange(new Rect(new Point(), pageSize));
ffixedPage.UpdateLayout();
PageContent fpageContent = new PageContent();
((IAddChild)fpageContent).AddChild(ffixedPage);
fixedDoc.Pages.Add(fpageContent);
IsFooterAdded = true;
}
if (IsFooterAdded)
{
break;
}
}
PrintFixedDocument(fixedDoc, printDialog);
}
private DataGrid GetDataGrid(DataGrid grid, double GridActualWidth, double PageWidthWithMargin)
{
DataGrid printed = new DataGrid();
// styling the grid
Style rowStyle = new Style(typeof(DataGridRow));
rowStyle.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.White));
rowStyle.Setters.Add(new Setter(Control.FontSizeProperty, FontSize));
if (IsBold) rowStyle.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.Bold));
rowStyle.Setters.Add(new Setter(Control.HeightProperty, RowHeight));
Style columnStyle = new Style(typeof(DataGridColumnHeader));
columnStyle.Setters.Add(new Setter(Control.FontSizeProperty, HeaderFontSize));
columnStyle.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Center));
columnStyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0, 0.5, 0, 1.5)));
columnStyle.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.White));
columnStyle.Setters.Add(new Setter(Control.BorderBrushProperty, Brushes.Black));
columnStyle.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.SemiBold));
printed.RowStyle = rowStyle;
printed.VerticalGridLinesBrush = Brushes.Black;
printed.HorizontalGridLinesBrush = Brushes.Black;
printed.FontFamily = new FontFamily("Arial");
printed.RowBackground = Brushes.White;
printed.Background = Brushes.White;
printed.Foreground = Brushes.Black;
// get the columns of grid
foreach (var column in grid.Columns)
{
if (column.Visibility != Visibility.Visible) continue;
DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.HeaderStyle = columnStyle;
textColumn.Header = column.Header;
textColumn.Width = column.ActualWidth / GridActualWidth * PageWidthWithMargin;
textColumn.Binding = ((DataGridTextColumn)column).Binding;
printed.Columns.Add(textColumn);
}
printed.BorderBrush = Brushes.Black;
return printed;
}
public void PrintFixedDocument(FixedDocument fixedDoc, PrintDialog printDialog)
{
XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printDialog.PrintQueue);
writer.Write(fixedDoc, printDialog.PrintTicket);
}
}

Why am i getting a System.NullReferenceException error in my code? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I'm currently working on an exercise for my c# class. I am having some trouble with one particular part and would really appreciate some help.
I am working on an exercise in which we are given an incomplete project file.
The project has multiple classes, this class is for controlling squares that are placed on the board.
namespace HareAndTortoise {
public partial class SquareControl : PictureBox {
public const int SQUARE_SIZE = 100;
private Square square; // A reference to the corresponding square object
private BindingList<Player> players; // References the players in the overall game.
private bool[] containsPlayers = new bool[6];//HareAndTortoiseGame.MAX_PLAYERS];
public bool[] ContainsPlayers {
get {
return containsPlayers;
}
set {
containsPlayers = value;
}
}
// Font and brush for displaying text inside the square.
private Font textFont = new Font("Microsoft Sans Serif", 8);
private Brush textBrush = Brushes.White;
public SquareControl(Square square, BindingList<Player> players) {
this.square = square;
this.players = players;
// Set GUI properties of the whole square.
Size = new Size(SQUARE_SIZE, SQUARE_SIZE);
Margin = new Padding(0); // No spacing around the cell. (Default is 3 pixels.)
Dock = DockStyle.Fill;
BorderStyle = BorderStyle.FixedSingle;
BackColor = Color.CornflowerBlue;
SetImageWhenNeeded();
}
private void SetImageWhenNeeded()
{
if (square is Square.Win_Square)
{
LoadImageFromFile("Win.png");
textBrush = Brushes.Black;
}
else if (square is Square.Lose_Square)
{
LoadImageFromFile("Lose.png");
textBrush = Brushes.Red;
}
else if (square is Square.Chance_Square)
{
LoadImageFromFile("monster-green.png");
}
else if (square.Name == "Finish")
{
LoadImageFromFile("checkered-flag.png");
}
else
{
// No image needed.
}
}
private void LoadImageFromFile(string fileName) {
Image image = Image.FromFile(#"Images\" + fileName);
Image = image;
SizeMode = PictureBoxSizeMode.StretchImage; // Zoom is also ok.
}
protected override void OnPaint(PaintEventArgs e) {
// Due to a limitation in WinForms, don't use base.OnPaint(e) here.
if (Image != null)
e.Graphics.DrawImage(Image, e.ClipRectangle);
string name = square.Name;
// Create rectangle for drawing.
float textWidth = textFont.Size * name.Length;
float textHeight = textFont.Height;
float textX = e.ClipRectangle.Right - textWidth;
float textY = e.ClipRectangle.Bottom - textHeight;
RectangleF drawRect = new RectangleF(textX, textY, textWidth, textHeight);
// When debugging this method, show the drawing-rectangle on the screen.
//Pen blackPen = new Pen(Color.Black);
//e.Graphics.DrawRectangle(blackPen, textX, textY, textWidth, textHeight);
// Set format of string.
StringFormat drawFormat = new StringFormat();
drawFormat.Alignment = StringAlignment.Far; // Right-aligned.
// Draw string to screen.
e.Graphics.DrawString(name, textFont, textBrush, drawRect, drawFormat);
// Draw player tokens (when any players are on this square).
const int PLAYER_TOKENS_PER_ROW = 3;
const int PLAYER_TOKEN_SIZE = 30; // pixels.
const int PLAYER_TOKEN_SPACING = (SQUARE_SIZE - (PLAYER_TOKEN_SIZE * PLAYER_TOKENS_PER_ROW)) / (PLAYER_TOKENS_PER_ROW - 1);
for (int i = 0; i < containsPlayers.Length; i++) {
if (containsPlayers[i]) {
int xPosition = i % PLAYER_TOKENS_PER_ROW;
int yPosition = i / PLAYER_TOKENS_PER_ROW;
int xPixels = xPosition * (PLAYER_TOKEN_SIZE + PLAYER_TOKEN_SPACING);
int yPixels = yPosition * (PLAYER_TOKEN_SIZE + PLAYER_TOKEN_SPACING);
Brush playerTokenColour = players[i].PlayerTokenColour;
e.Graphics.FillEllipse(playerTokenColour, xPixels, yPixels, PLAYER_TOKEN_SIZE, PLAYER_TOKEN_SIZE);
}
}//endfor
}
}
}
The program trips up at:
else if (square.Name == "Finish")
{
LoadImageFromFile("checkered-flag.png");
}
I know it is because of square.name but from going through the code, I cant see why square.Name is not recognizable.
Square is passed from another class using this method
private void SetUpGuiGameBoard()
{
for (int i = 0; i <= 55; i++)
{
Square q = Board.GetGameBoardSquare(i);
SquareControl sq = new SquareControl(q, null);
int coloumn;
int row;
if (i == 0)
{
BackColor = Color.BurlyWood;
}
if (i == 55)
{
BackColor = Color.BurlyWood;
}
MapSquareNumToTablePanel(i, out coloumn, out row);
tableLayoutPanel1.Controls.Add(sq, coloumn, row);
}
and Squares are created in this class
private static Square[] gameBoard = new Square[56];
static public void SetUpBoard()
{
for (int i = 1; i == 55; i++)
{
gameBoard[i] = new Square("Ordinary Square", i);
}
gameBoard[0] = new Square("Start", 0);
gameBoard[4] = new Square.Lose_Square("Lose Square", 4);
gameBoard[5] = new Square.Chance_Square("Chance Square", 5);
gameBoard[9] = new Square.Win_Square("Win Square", 9);
gameBoard[11] = new Square.Chance_Square("Chance Square", 11);
gameBoard[14] = new Square.Lose_Square("Lose Square", 14);
gameBoard[17] = new Square.Chance_Square("Chance Square", 17);
gameBoard[19] = new Square.Win_Square("Win Square", 19);
gameBoard[24] = new Square.Lose_Square("Lose Square", 24);
gameBoard[29] = new Square.Win_Square("Win Square", 29);
gameBoard[34] = new Square.Lose_Square("Lose Square", 34);
gameBoard[35] = new Square.Chance_Square("Chance Square", 35);
gameBoard[39] = new Square.Win_Square("Win Square", 39);
gameBoard[44] = new Square.Lose_Square("Lose Square", 44);
gameBoard[47] = new Square.Chance_Square("Chance Square", 47);
gameBoard[49] = new Square.Win_Square("Win Square", 49);
gameBoard[53] = new Square.Chance_Square("Chance Square", 53);
gameBoard[55] = new Square("Finish", 56);
}
public static Square GetGameBoardSquare(int n)
{
return gameBoard[n];
}
public static Square StartSquare()
{
return gameBoard[0];
}
public static Square NextSquare(int n)
{
return gameBoard[(n+1)];
}
}
The answer already provided is the best way for prevention of any null reference exception. For more clarification I can suggest you to check the call stack at the point the debugger reaches the SquareControl constructor. At this point you should check why the Square object being passed in is a 'NULL'. That will lead you to the root cause of the problem. Hope this helps.

Chart font style always bold when background is transparent

I have a basic asp.net chart writing into the response stream.
Changing BackColor to Color.Transparent and every text being bold automaticly. Searched many posts/forums about this issue but couldnt find any solution.
This my Chart builder Code.
public static void BuildChart(Chart chart, IEnumerable<MultiMeasureData> source, Measure[] measures,bool transparent)
{
var ca = chart.ChartAreas.FirstOrDefault();
if (ca == null)
chart.ChartAreas.Add(ca = new ChartArea());
//added for transparency support.
ca.BackImageTransparentColor = Color.White;
ca.BackColor = Color.Transparent;
Series s = new Series("Ölçümler");
s.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
chart.Series.Add(s);
var leg = new Legend("legend1");
leg.Docking = Docking.Top;
//added for transparenct support.
leg.BackColor = Color.Transparent;
leg.Font = new Font("Arial", 8, FontStyle.Regular);
chart.Legends.Add(leg);
chart.Palette = System.Windows.Forms.DataVisualization.Charting.ChartColorPalette.Berry;
//Transparency.
chart.BackColor = transparent ? Color.Transparent : Color.White;
//chart.BackSecondaryColor = Color.FromArgb(187, 205, 237);
//chart.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.LeftRight;
if (source != null)
{
if (measures.Length > 0)
{
ca.AxisX.LabelStyle.Format = "dd.MM.yy";
ca.AxisX.MinorGrid.Enabled = true;
ca.AxisX.MinorGrid.Interval = 12;
ca.AxisX.MinorGrid.IntervalType = DateTimeIntervalType.Hours;
ca.AxisX.MinorGrid.LineColor = Color.LightGray;
ca.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.HorizontalCenter;
// ca.BackColor = Color.FromArgb(134, 218, 239);
ca.AxisY.LabelStyle.Format = "{0}" + measures.First().Type.Unit;
ca.AxisY.LabelStyle.ForeColor = Color.Black;
ca.AxisY.LabelStyle.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
ca.AxisX.LabelStyle.ForeColor = Color.Black;
ca.AxisX.LabelStyle.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
ca.AxisX.MajorGrid.LineColor = Color.Silver;
ca.AxisY.MajorGrid.LineColor = Color.Silver;
// var tm = (e - s).TotalMinutes / 10;
var data = source
.Select(a =>
{
var ret = new { Time = a.Time, Values = new double?[measures.Length] };
for (int i = 0; i < measures.Length; i++)
ret.Values[i] = a.Values[i].HasValue ? a.Values[i] / measures[i].Type.ValueScale:null;
return ret;
}
).OrderBy(a => a.Time);
var times = data.Select(a => a.Time).ToArray();
for (int i = 0; i < measures.Length; i++)
{
var serie = new Series(measures[i].Type.Name) { ChartType = SeriesChartType.Spline };
serie.XValueType = ChartValueType.DateTime;
serie.ShadowColor = Color.Gray;
serie.BorderWidth = 2;
serie.ShadowOffset = 1;
serie.Points.DataBindXY(times, new[] { data.Select(a => a.Values[i]).ToArray() });
serie.LegendText = measures[i].Type.Name;
serie.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
chart.Series.Add(serie);
}
}
}
}
this is mainly stream writer method using BuildChart method
public static void SaveChart(System.IO.Stream stream, System.Drawing.Imaging.ImageFormat format, int w, int h, IEnumerable<MultiMeasureData> source, Measure[] measures,bool transparent)
{
var c = new Chart() { Width = w, Height = h};
BuildChart(c, source, measures,transparent);
c.SaveImage(stream, format);
}
And here is both results.
Background.White (transparent parameter is false)
Background.Transparent (transparent parameter is true)
look at this answer :MS Chart Control: Formatting Axis Labels
This solved my problems
Regards
Nemanja

Categories

Resources