Why does this textblock only display "TextBlock" as its text? - c#

Really new and learning C# and following along some training video from PluralSight. Great videos, except you cannot ask questions, of course and I am not understanding why what I am seeing is different that what his screen is displaying even though I typed exactly what he has.
Textbox is named "Output". Initially, the actions were directly in the MainWindow constructor (which he explained is not good practice, so we moved it. Initially, this worked as it should:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Employee e1 = new Employee();
e1.Name = "Mike";
Employee e2 = new Employee();
e2.Name = "Miller";
Output.Text = e1.Name + " " + e2.Name;
}
}
}
This would display "Mike Miller" in the TextBlock.
However, when we moved it to this, all it says for the text is "TextBlock"
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Employee e1 = new Employee();
e1.Name = "Mike";
Employee e2 = new Employee();
e2.Name = "Miller";
Output.Text = e1.Name.Length + " " + e2.Name.Length;
}
}
}
Am I missing something simple here?
Thanks!

As Nico Schertler stated, verify that you subscribed to Loaded event of Window:
<Window ... Loaded="MainWindow_Loaded">
...
</Window>
In first case your code runs, because constructor of Window is called when Window is created. In second case, event handler is not called by default. You should subscribe to this event.

If you take the .Length off the two strings, it should work. You're concatenating integers with a string using "+" and that doesn't work so well.
Output.Text = e1.Name + " " + e2.Name;

Answer is very certain from your question:
Firstly if you are expecting output to be "Mike Miler" change your code to the one which is posted by Bravan.
Secondly you need to add Loaded event to your MainWindow declaration in XAML.
other than that nothings wrong there...!!!
Happy Coding...!! :)

Related

UWP - CheckBox or Button is not visible

Using
Jetbrains Rider
Universal Windows Platform
Problem
The window is visible, but the buttons are not visible.
Question
How can I fix the problem?
Source code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace UWP_TEST1
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
StackPanel stackPanel1 = new StackPanel();
CheckBox checkBox1 = new CheckBox();
checkBox1.Content = "I agree to the terms of service.";
stackPanel1.Children.Add(checkBox1);
}
}
}
You forgot to add the StackPanel stackPanel1 to the page. Setting the content of your page to the stackPanel1 will show the buttons. You can do this by adding Content=stackPanel in the constructor.

How to display the print dialog box for crystal report viewer in wpf

In my print window i have written the below code:
public void ShowReport(ReportDocument rp)
{
MyCrystalReportsViewer.ViewerCore.ReportSource = rp;
this.WindowState = WindowState.Maximized;
MyCrystalReportsViewer.ViewerCore.PrintReport();
}
I am calling this method from another class,but when i'm displaying the print window, the print dialog box was not appearing by default.
Can any one solve my problem to display the print dialog box when I am calling print window.
Thanks in advance
Maybe this will help. I simply use the print mechanism that is provided in the Report Viewer to begin with, not try to make my own print dialogs. Also, I found Crystal's WPF implementation to be poor and lacking many features i needed, and therefore i hosted the WinForm version inside a WindowsFormsHost instead. Please try this route, as I said the WPF version was very poor and support online at Crystal's website is horrendous. Here is my code-
XAML where i host the WindowsFormHost (crystal's newer WPF version left many options out that i needed):
<Window x:Class="Example.Views.Reports.ReportView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStartupLocation="CenterOwner"
xmlns:Viewer="clr-namespace:CrystalDecisions.Windows.Forms;assembly=CrystalDecisions.Windows.Forms"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
Title="{Binding WindowTitle}" >
<!--xmlns:Viewer="clr-namespace:SAPBusinessObjects.WPF.Viewer;assembly=SAPBusinessObjects.WPF.Viewer"-->
<Grid>
<!--<Viewer:CrystalReportsViewer Name="ReportViewer"/>-->
<WindowsFormsHost>
<Viewer:CrystalReportViewer x:Name="ReportViewer"/>
</WindowsFormsHost>
</Grid>
</Window>
code behind that makes it work:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Bill.Constants;
using Bill.Models.Reports;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using CrystalDecisions.Windows.Forms;
namespace Example.Views.Reports
{
/// <summary>
/// Interaction logic for ReportView.xaml
/// </summary>
public partial class ReportView : Window, INotifyPropertyChanged
{
public ReportView(Report report)
{
InitializeComponent();
//WPF - not needed
//this.ReportViewer.Owner = Window.GetWindow(this); //added to fix null parameter window bug in Crystal report
if (Application.Current.MainWindow.IsLoaded)
{
this.Owner = Application.Current.MainWindow;
}
WindowTitle = report.DisplayName;
this.DataContext = this;
ShowReport(report.FileInfo.FullName);
}
private string _windowTitle;
/// <summary>
/// Name of the report, shown in Window Title
/// </summary>
public string WindowTitle
{
get { return _windowTitle; }
set
{
if (_windowTitle != value)
{
_windowTitle = value;
FirePropertyChanged("WindowTitle");
}
}
}
/// <summary>
/// Show the selected report
/// </summary>
/// <param name="reportPath"></param>
private void ShowReport(string reportPath)
{
ReportDocument report = new ReportDocument();
if (!String.IsNullOrEmpty(reportPath))
{
TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables;
report.Load(reportPath);
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionStrings.CurrentConnection.ConnectionString); //from config.xml
crConnectionInfo.ServerName = builder.DataSource;
crConnectionInfo.DatabaseName = builder.InitialCatalog;
crConnectionInfo.IntegratedSecurity = true;
CrTables = report.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}
//WinForms values
ReportViewer.ReportSource = report;
ReportViewer.EnableDrillDown = false;
//ReportViewer.AllowedExportFormats=ExportFormatType.
ReportViewer.ShowLogo = false;
ReportViewer.ShowRefreshButton = false;
ReportViewer.ShowParameterPanelButton = false;
ReportViewer.ShowGroupTreeButton = false;
ReportViewer.UseWaitCursor = false;
ReportViewer.ToolPanelView = ToolPanelViewType.None;
//report.Refresh();
}
}
#region INotifyPropertyChange
public event PropertyChangedEventHandler PropertyChanged;
protected void FirePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
I did it in two ways, using a window form, I call from the page to window form, inside the window form I embed the CrystalReportViewer and the window form loads the crystal report, it is the easiest and most practical way I have been, code:
Dim rpt As New rpt_Crystal_report
Dim frm As New windowform
Frm.CrystalReportViewer1.ReportSource = rpt
Frm.Refresh ()
Frm.ShowDialog ()
Frm.Dispose ()
And the other way to load the crystal report in a page I do the following:
Example, I have page 1 and page 2, inside page 1 I have a print button, which has the following code,
Dim p1 As New page2
NavigationService.Navigate (p1)
And inside page 2, I embed the crystalreportviewer the same as I did in the windowform, but inside the load of page 2 I have the following code,
Dim rpt As New rpt_Crystal_report
Me.CrystalReportsViewer1.ViewerCore.ReportSource = rpt
And in this way I managed to show the report on a page,
If someone has another idea better and it works, it would be excellent, regards!

Create a custom control in Corel Draw X6 using only VSTA

I am in the process of creating a plugin (or addin) for CorelDraw X6 using VSTA (Visual Studio for Applications) because I like C# and .NET library. I would like to have a button in CorelDraw toolbar, so when a user clicks this button some action happens, for example, a form is showed. For that I use predefined solution VSTAGlobal, that is there for me when I start CorelDraw. Unfortunately, there is NO official documentation (WTF!!!!!) for VSTA in CorelDraw, instead we have VBA (Visual Basic for Applications) documentation and CorelDraw Object Model. I googled a lot and found a few links: some forum post and YouTube video tutorial. The problem is, both guys there create their CustomControl (a buton for example) and simply build it as *.dll and then use VBA script to add the CustomControl to CorelDraw toolbar like this
Sub addLineWidthControl()
Call FrameWork.CommandBars("Standard").Controls. '
AddCustomControl("MyNameSpace.MyCustomControlClass", '
"MyCustomControlAssembly.dll")
End Sub
So, my question is: is there any way to do this using only VSTA?
Additional info:
For example, in the default solution VSTAGlobal there is a Main class with [CgsAddInModule] attribute:
[CgsAddInModule]
public partial class Main
{
private Corel.Interop.VGCore.Application app;
// some other code here...
}
This class has a constructor (note, default and provided by CorelDraw):
[CgsAddInConstructor]
public Main(object _app)
// this constructor probably gets an instance
// of CorelDraw application object.
{
app = _app as Corel.Interop.VGCore.Application;
// will it work if I add some code here?
}
Maybe this is the place where I should add something like this:
app.FrameWork.CommandBars["Standard"]
.Controls.AddCustomControl("MyCustomControlClass");
I did some experiments with this last line of code. I obtained that the Count of Controls is increasing, but still MyCustomControl does not show up in the toolbar.
There is a way to use only C# (I tested this in Corel X8 but it should work in any version that has VSTA). It is a 2 part process though. First you will need to open Macro Manager in Corel and edit the VSTAGlobal solution. For example, if you want to add a button and a slider, add this method:
[CgsAddInMacro]
public void Add()
{
string controlAssembly = #"C:\VSTS\ScratchProjects\CoreDrawPoC\CoreDrawPoC\bin\Debug\CoreDrawPoC.dll";
var mySlider = app.FrameWork.CommandBars["Standard"].Controls.AddCustomControl("CoreDrawPoC.MySlider", controlAssembly);
mySlider.Caption = "Border Sizing Slider Caption";
mySlider.ToolTipText = "Border Sizing Slider Tooltip";
var myButton = app.FrameWork.CommandBars["Standard"].Controls.AddCustomControl("CoreDrawPoC.ButtonSample", controlAssembly);
myButton.Caption = "Rectanlge Selector";
mySlider.ToolTipText = "Rectanlge Selector Tooltip";
}
Once you add this code, you will need to add a .dll for a solution to the folder listed above. Open Visual Studio 2015 and create a new project (mine was named CoreDrawPoC). It needs to be a WPF User Control Library project. Create 2 .xaml files with. First will be the slider:
<UserControl x:Class="CoreDrawPoC.MySlider"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CoreDrawPoC"
mc:Ignorable="d" >
<Slider x:Name="mySlider" Width="100" Minimum=".5" Maximum="10" TickFrequency=".5" IsSnapToTickEnabled="True" ValueChanged="mySlider_ValueChanged"/>
</UserControl>
Code behind is:
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace CoreDrawPoC
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class MySlider : UserControl
{
Corel.Interop.VGCore.Application appDraw = null;
public MySlider()
{
InitializeComponent();
}
public MySlider(object app)
{
InitializeComponent();
appDraw = (Corel.Interop.VGCore.Application)app;
}
private void mySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (appDraw != null && appDraw.ActiveDocument != null && appDraw.ActiveShape != null)
{
double width = appDraw.ConvertUnits((double)e.NewValue, Corel.Interop.VGCore.cdrUnit.cdrPoint, Corel.Interop.VGCore.cdrUnit.cdrInch);
appDraw.ActiveSelectionRange.SetOutlineProperties(width);
}
}
}
}
Then create the button:
<UserControl x:Class="CoreDrawPoC.ButtonSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CoreDrawPoC"
mc:Ignorable="d">
<Button x:Name="buttonSample" Click="buttonSample_Click" Width="24" Height="24" >
<Button.Template>
<ControlTemplate>
<Image Source="C:\CorelIcons\Two.bmp"/>
</ControlTemplate>
</Button.Template>
</Button>
</UserControl>
Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace CoreDrawPoC
{
/// <summary>
/// Interaction logic for ButtonSample.xaml
/// </summary>
public partial class ButtonSample : UserControl
{
Corel.Interop.VGCore.Application appDraw = null;
public ButtonSample()
{
InitializeComponent();
}
public ButtonSample(object app)
{
InitializeComponent();
appDraw = (Corel.Interop.VGCore.Application)app;
}
private void buttonSample_Click(object sender, RoutedEventArgs e)
{
SelectOfType("rectangle");
}
private void SelectOfType(string strType)
{
string strQuery = null;
Corel.Interop.VGCore.ShapeRange srGroup = default(Corel.Interop.VGCore.ShapeRange);
Corel.Interop.VGCore.ShapeRange srTopOnly = default(Corel.Interop.VGCore.ShapeRange);
strQuery = "#type='" + strType + "'";
srGroup = appDraw.ActivePage.Shapes.FindShapes("", 0, true, strQuery);
srTopOnly = appDraw.ActivePage.Shapes.FindShapes("", 0, false, strQuery);
srTopOnly.CreateSelection();
appDraw.ActivePage.Shapes.FindShapes("", 0, false, strQuery).CreateSelection();
//if (srTopOnly.Count == srGroup.Count)
//{
// lblWarning.Visibility = System.Windows.Visibility.Hidden;
//}
//else
//{
// lblWarning.Visibility = System.Windows.Visibility.Visible;
//}
}
}
}
Once that is done, you will want to compile the code. Also, you will want to create the image C:\CorelIcons\Two.bmp. It is just a 24x24 bitmap that looks however you want it to look. Then compile the project. You will need to this will CorelDraw closed.
Once it compiles successfully, you will want to go and run your VSTA macro to add the button and slider. This macro will only need to be run 1 time! After than, it will connect directly to the code in your dll. If you change anything in the dll and update it while Corel is closed, it changes it. This includes the images.
Finally, I learned how to do this from 2 blog posts and I only changed it to add a button to the Standard command bar and to use purely C#. Those posts are:
https://forum.oberonplace.com/blog.php?b=165
https://forum.oberonplace.com/blog.php?b=166

Loading simples text file list on listview C#

so i was working with a text file data that contains a lot of simple lines and i want to put them on the list view exatly the same way as the listbox do. I need that because after i loading a long list on listbox, even it showing all my items, i cannot make a FindString() on it. i attached the comand to a combo box, and with other small lists it worked, but with this larger, seems that index reference doesn't work because of listbox limit.
So i was wondering if is possible to put, as example:
line1
line2
line3
line4
My text files hasn't this dots, i pu them just to make the example vertical.
On a list view. i used on listbox the method file.readllines to get it loading to it, and if exists a string find method to help me get the text on the lines. What should i do?
You can write the searcher you want by yourself.
It's very easy.
Just iterate on each data that exists in your ListView.
Then check your condition through an if-statement and do anything you want with the result!
Like this :
this.listView1.Items.Add("Test1");
this.listView1.Items.Add("Test2");
int Index = 0;
foreach (ListViewItem t in this.listView1.Items)
{
if (t.Text == "Test1")
Index = t.SelectedIndex;
break;
}
this.listView1.Items[Index].Selected = true;
I added couple of items to the ListView then iterate on it's items using a foreach, filter the items using an if-statement and finally show the item that I want.
You have to add an eventhandler. For example for the event of the ListView Load.
Then in the event handler you could load the contents of the file using the File class.
For example you could do it like this:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// ListView Loaded - Eventhandler
private void ListView_Loaded(object sender, RoutedEventArgs e)
{
string[] lines = File.ReadAllLines("E:\\test.txt");
foreach (string line in lines)
{
listview.Items.Add(line);
}
}
}
}
I have just tested the solution and it works fine.
I hope I got your intention.
thanks a lot of helping me, but i gandle it, i search a lot for extending the limit of listbox but no one was capable to help me out, but with your "foreach" code, this new way to search helped me to select my string on listbox, here's the code using a combo box to evertime updated get me the selected value from a gourgeous list:
declaring:
string result;
and then the combobox event:
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
foreach (string item in listBox1.Items)
{
listBox1.SelectionMode = SelectionMode.One;
if (item == comboBox1.Text)
{
result = item;
}
}
listBox1.SelectedItem = result;
}

Where are the Properties gone ? I did Properties.Resources but properties not exist

This is the code in my class i have:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
namespace Magnifier20070401
{
public partial class MagnifierForm : Form
{
public MagnifierForm(Configuration configuration, Point startPoint)
{
InitializeComponent();
//--- My Init ---
mConfiguration = configuration;
FormBorderStyle = FormBorderStyle.None;
ShowInTaskbar = mConfiguration.ShowInTaskbar;
TopMost = mConfiguration.TopMostWindow;
Width = mConfiguration.MagnifierWidth;
Height = mConfiguration.MagnifierHeight;
// Make the window (the form) circular
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(ClientRectangle);
Region = new Region(gp);
mImageMagnifier = Properties.Resources.magnifierGlass;
On the Properties im getting: Error 1 The name 'Properties' does not exist in the current context
I added this Form as Existing item to my project and im getting an error on this Properties.
And i have the magnifierGlass image in the Resources.
Found it needed to add my project name before the properties:
mImageMagnifier = ScreenVideoRecorder.Properties.Resources.magnifierGlass;
Now it's working thanks.

Categories