I have this code. When I need to print my report, it shows me a Print Dialog. I want to select my print name by code, and print my report without showing PrintDialog.
This is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Printing;
namespace POS.Reports
{
public partial class ProductsReceiptPreview : Form
{
BindingSource _data;
string _total, _cashr, _cashc;
public ProductsReceiptPreview(BindingSource data, string total,
string cashr, string cashc)
{
InitializeComponent();
_total = total; _cashr = cashr; _cashc = cashc;
_data = data;
}
private void ProductsReceipt_Load(object sender, EventArgs e)
{
DataReceiptBindingSource.DataSource = _data;
Microsoft.Reporting.WinForms.ReportParameter[] param = new
Microsoft.Reporting.WinForms.ReportParameter[]
{
new Microsoft.Reporting.WinForms.ReportParameter("ptotal",
_total),
new Microsoft.Reporting.WinForms.ReportParameter("pcashr",
_cashr),
new Microsoft.Reporting.WinForms.ReportParameter("pcashc",
_cashc),
new Microsoft.Reporting.WinForms.ReportParameter
("pdate",DateTime.Now.ToString())
};
this.rptProductsReceipt.LocalReport.SetParameters(param);
this.rptProductsReceipt.RefreshReport();
this.rptProductsReceipt.ZoomMode =
Microsoft.Reporting.WinForms.ZoomMode.PageWidth;
}
private void btnReports_Click(object sender, EventArgs e)
{
rptProductsReceipt.PrintDialog();
}
}
}
i never use your method but i use this
rptProductsReceipt.PrintToPrinter(1, false, 0, 0);
after using adapter and data table
Related
Hello it is probably easy question for you, I'm a beginner and I'm making my own simple game and I want to use a Class:Gamer, which I want to initialize in MainWindow(Form1.cs) from a save file. From then, I want to use it on another Forms aswell, but somehow I can't make the instance go public.
Could you tell me what I'm doing wrong? Or is there another way how to solve this?
Thank you :)
Code on Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Text;
using System.IO;
namespace THE_GAME
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static Gamer Player;
private void MainWindow_Load(object sender, EventArgs e)
{
//load from savefile lvl;hp;money;gun;armor,name
string allData = File.ReadAllText("../../saveFile/save.txt");
string[] dataFromSave = new string[5];
dataFromSave = allData.Split(';');
Player = new Gamer(dataFromSave[0], dataFromSave[1], dataFromSave[2], dataFromSave[3], dataFromSave[4], dataFromSave[5]);
}
}
}
Code on secondForm2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Text;
namespace THE_GAME
{
public partial class Statistics : Form1
{
public Statistics()
{
InitializeComponent();
}
private void Statistics_Load(object sender, EventArgs e)
{
//labels stats
labelName.Text = Form1.Player.GetName();
labelHealth.Text = Form1.Player.GetHealth().ToString();
labelMoney.Text = Form1.Player.GetMoney().ToString();
}
private void buttonBack_Click(object sender, EventArgs e)
{
MainMenu menu = new MainMenu();
menu.Show();
this.Close();
}
}
}
Thank you for your time.
To get at the Gamers Player object from a different Form just do
Form1.Player;
ie
var nam = Form1.Player.Name;
Form1.Player.Die();
etc
PS As I said in a comment - its extremely odd to dereive a form of yours from another one of your forms. Like this
public partial class Statistics : Form1
A project that I received from school has simple instructions: Create a working 3 form C# application. I decided to create a form which will let the user choose from 3 different options (In this case: 1 ticket, 2 tickets, and 3 tickets). Then it will switch to a 2nd form and also let the user choose from 3 options (In this case: 1 bag of popcorn, A large soda, and a bag of chips). The Problem I am having is when it tries to display the total cost its always ends up being 0. I would really appreciate any help.
Code:
Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WongGregory9_part3ThreeForms
{
public partial class movieForm : Form
{
public movieForm()
{
InitializeComponent();
}
private void exitButton_Click(object sender, EventArgs e)
{
//Close form
this.Close();
}
private void displayButton_Click(object sender, EventArgs e)
{
//create a variable named snack for snackForm
snackForm snack = new snackForm();
//show the form snack
snack.ShowDialog();
}
}
Form2(snackForm):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WongGregory9_part3ThreeForms
{
public partial class snackForm : Form
{
//define varible ticket as 50
int ticket = 50;
//define varible twoTicket as 90
int twoTickets = 90;
//define varible threeTicket as 130
int threeTickets = 130;
//define varible popcorn as 65
int popcorn = 65;
//define varible soda as 30
int soda = 30;
//define varible chips as 40
int chips = 40;
//define varible ticketCost
int ticketCost;
//define varible snackCost
int snackCost;
//define varible totalCost;
int totalCost;
//create a variable named movie for movieForm
movieForm movie = new movieForm();
public snackForm()
{
InitializeComponent();
}
private void snackForm_Load(object sender, EventArgs e)
{
//if ticketRadioButton is checked then..
if (movie.ticketRadioButton.Checked)
{
//ticketCost = ticket
ticketCost = ticket;
}
//if ticketRadioButton2 is checked then..
if (movie.ticketRadioButton2.Checked)
{
//ticketCost = twoTicket
ticketCost = twoTickets;
}
//if ticketRadioButton3 is checked then..
if (movie.ticketRadioButton3.Checked)
{
//ticketCost = threeTicket
ticketCost = threeTickets;
}
//if popcornRadioButton is checked then..
if (popcornRadioButton.Checked)
{
//snackCost = popcorn
snackCost = popcorn;
}
//if sodaRadioButton is checked then..
if (sodaRadioButton.Checked)
{
//snackCost = soda
snackCost = soda;
}
//if chipsRadioButton is checked then..
if (chipsRadioButton.Checked)
{
//snackCost = chips
snackCost = chips;
}
}
private void button1_Click(object sender, EventArgs e)
{
//close form
this.Close();
}
private void displayButton_Click(object sender, EventArgs e)
{
//create a variable named movie for movieForm
displayForm display = new displayForm();
//totalCosts equals ticketCost plus snackCost
totalCost = ticketCost + snackCost;
//display totalCost to displayLabel
display.displayLabel.Text = totalCost.ToString();
//show the dialog entered into displayForm
display.ShowDialog();
}
}
Form3(displayForm):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WongGregory9_part3ThreeForms
{
public partial class displayForm : Form
{
public displayForm()
{
InitializeComponent();
}
}
Yup, two issues I can see, both in snackForm:
As per Sergey's comment, you are creating a new instance of movieForm, which doesn't know anything about the data on the original movieForm instance. You need to pass data from the original movieForm to your snackForm, in the same way as you pass the total cost from snackForm to displayForm.
You are checking the radio button selections in snackForm while the form is loading, i.e. before the user has had a chance to click them. Move these checks into snackForm.displayButton_Click
Here's the relevant code:
ClickMeGame.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary
{
public class ClickMeGame
{
public OnClickMe onClickMeCallback;
public int score;
public ClickMeGame()
{
score = 0;
}
private void IncrementScore()
{
score++;
}
}
}
ClickMeCallBackDefinitions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary
{
public delegate void OnClickMe();
}
MainWindow.cs (Windows Form)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ClassLibrary;
namespace ClickMe
{
public partial class mainWindow : Form
{
private ClickMeGame game;
public mainWindow()
{
InitializeComponent();
game = new ClickMeGame();
game.onClickMeCallback = clickMeButton_Click();
}
private void clickMeButton_Click(object sender, EventArgs e)
{
UpdateUI();
}
private void UpdateUI()
{
scoreLabel.Text = string.Format("The score is: {0}", game.score);
}
}
}
So what I'm trying to do is, when the user clicks a button present on the form, I want a label on the form to update with the game score which increments with every click.
I'm learning about/want to be able to do this with delegates in that I want to separate the project into 2 tiers; Presenation and Logic. I know it's unnecessary to do so, but I'd like to make it such that when you click the button, the Windows Form receives information about the game score via delegates/callback methods. I'm unsure how to do this, but I tried making the callback definition and referencing it, but I'm lost from there.
Assuming that the UI button uses the click event clickMeButton_Click then here you go.
public partial class mainWindow : Form
{
private ClickMeGame game;
public mainWindow()
{
InitializeComponent();
game = new ClickMeGame();
game.onClickMeCallback = param => UpdateUI();
}
private void clickMeButton_Click(object sender, EventArgs e)
{
game.onClickMeCallback.Invoke();
}
private void UpdateUI()
{
scoreLabel.Text = string.Format("The score is: {0}", game.score);
}
}
I have a problem changing text from another class in another namespace. I have the first Form1 class :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
static Form1 mainForm;
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
public static String LinkToApi = "http://google.com/api/";
public static Comunicator comunicator;
public static int debug = 5;
public Form1()
{
InitializeComponent();
AllocConsole(); // allow console
if(Form1.debug >= 3) Console.WriteLine("Application started");
comunicator = new Comunicator();
mainForm = this;
}
private void TestButton_Click(object sender, EventArgs e)
{
TestButton.Text = "Loading";
comunicator.TestConnection();
}
}
}
and this Comunicator class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Collections.Specialized;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
namespace WindowsFormsApplication1
{
public class Comunicator
{
private String action = "idle";
public static Thread Start(Action action)
{
Thread thread = new Thread(() => { action(); });
thread.Start();
return thread;
}
public Comunicator()
{
}
public void TestConnection()
{
if (Form1.debug >= 3) Console.WriteLine("Testing connection");
// thread test
Start(new Action(ApiTest));
}
public void ApiTest()
{
if (Form1.debug >= 3) Console.WriteLine("API test begin");
// Create a request for the URL.
WebRequest request = WebRequest.Create("http://www.bogotobogo.com/index.php");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
// Console.Read();
if (Form1.debug >= 3) Console.WriteLine("API test end");
// Form1.StaticTestButton.Text = "Loaded"; <---- CHANGE HERE
}
}
}
which is not even a form class (I want to keep everything nice and clean). I want to change the TestButton text into "LOADED" but i get an error when I try to do that as if Form1.TestButton does not exist in Comunicator class.
I have tried to instantiate the class, I made a couple of variables static ... nothing, still getting error.
What is the problem? How may I solve this?
The request must be asynchronous, that's why I am using threads.
You should separate concerns, and you shouldn't communicate with UI in class which is not related to UI.
You should rewrite your code.
But as quick fix you should do the following.
In class Comunicator, you can do such field.
private readonly Action<string> _notifySimpleMessageAction;
Then add to Communicator constructor parameter notifyFunction. Code in constructor:
_notifySimpleMessageAction = notifyFunction
After that you should create Communicator in following manner:
communicator = new Communicator((notification)=>
{
StaticTestButton.BeginInvoke((MethodInvoker)(() => StaticTestButton.AppendText(notification)));
});
Then at the end of your method you should do
_notifySimpleMessageAction("Loaded")
Controller class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ControllerDemonstrator
{
public class Controller
{
public event EventHandler CommunicatorDataLoaded;
public event EventHandler FormTestConnection;
private Form1 _form;
private Communicator _communicator;
public Form1 MainForm
{
get { return _form; }
}
public Controller()
{
_form = new Form1(this);
_form.TestConnection += _form_TestConnection;
_form.FormClosed += _form_FormClosed;
_communicator = new Communicator(this);
_communicator.DataLoaded += _communicator_DataLoaded;
}
public void Start()
{
_form.Show();
}
void _form_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
{
// put any code to clean up the communicator resources (if needed) here
// --------------------------------------------------------------------
_communicator = null;
// Then exit
// ---------
Application.Exit();
}
private void _communicator_DataLoaded(object sender, EventArgs e)
{
if (null != CommunicatorDataLoaded)
{
CommunicatorDataLoaded(sender, e);
}
}
private void _form_TestConnection(object sender, EventArgs e)
{
if (null != FormTestConnection)
{
FormTestConnection(sender, e);
}
}
}
}
Basic form with one button (_testButton):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ControllerDemonstrator
{
public partial class Form1 : Form
{
public event EventHandler TestConnection;
public Form1(Controller controller)
{
InitializeComponent();
controller.CommunicatorDataLoaded += controller_CommunicatorDataLoaded;
}
void controller_CommunicatorDataLoaded(object sender, EventArgs e)
{
_testButton.Text = "Loaded";
}
private void _testButton_Click(object sender, EventArgs e)
{
if (null != TestConnection)
{
TestConnection(this, new EventArgs());
}
}
}
}
Communicator class (everything has been stripped out, you will need to add in your logic):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ControllerDemonstrator
{
public class Communicator
{
public event EventHandler DataLoaded;
public Communicator(Controller controller)
{
controller.FormTestConnection += controller_FormTestConnection;
}
private void controller_FormTestConnection(object sender, EventArgs e)
{
// put your code that does the connection here
// -------------------------------------------
if (null != DataLoaded)
{
DataLoaded(this, new EventArgs());
}
}
}
}
And in your Program.cs (assuming that is how you are starting your application):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ControllerDemonstrator
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Controller c = new Controller();
Application.Run(c.MainForm);
}
}
}
With this kind of design, the communicator doesn't know about the form and vice verse. You can expand it out to have different kind's of communicators/forms/etc and have the controller keep track of everything. It is also much easier to test code like this as you can test each separate piece on it's own since they don't depend on each other. This is a quick and dirty implementation. Do some research on the Model View Controller design pattern (not Microsoft MVC for asp.Net, but the actual design pattern). It is more code up-front to code an application with the MVC design pattern but it makes it easier to test and more maintainable.
I have created a WCF service which sends an sms by using the supplied values. This then return XML in a string variable. I have managed to get the string loaded into an XmlDocument but then when I try and load it onto a Webform control I get an error because the XmlDocument is in memory and does not have a physical path. How can I get this loaded into my webform control(WB_XMLOut). Please see my code below what I have tried.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LeadProcessTest.LeadProcessor;
using System.Xml;
namespace LeadProcessTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BT_Process_Click(object sender, EventArgs e)
{
LeadProcessorClient LP = new LeadProcessorClient();
string UName = Convert.ToBase64String(Encoding.UTF8.GetBytes(TB_UName.Text));
string PWord = Convert.ToBase64String(Encoding.UTF8.GetBytes(TB_Pass.Text));
string XMLIn = Convert.ToBase64String(Encoding.UTF8.GetBytes(TB_XMLin.Text));
LP.Open();
string Result = LP.Lead_Processing(UName, PWord, XMLIn);
LP.Close();
XmlDocument XML = new XmlDocument();
XML.LoadXml(Result);
WB_XMLOut.Url = new Uri(XML);
}
}
}