[英]C# forms: how do I print out a CSV file which is selected using a different button
Goal: Direct print a CSV file which is selected from another button on my forms application目标:直接打印一个 CSV 文件,该文件是从我的 forms 应用程序的另一个按钮中选择的
Problem: I don't know how to tell amy btnPrintFile_click method the FileName coming from another method in form1.cs问题:我不知道如何告诉 amy btnPrintFile_click 方法 FileName 来自 form1.cs 中的另一个方法
Any help would be appreciated, Im new to forms in c#任何帮助将不胜感激,我是 c# 中 forms 的新手
public void openCVSFile(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = false;
ofd.Filter = "CSV files (*.csv)|*.csv";
ofd.FilterIndex = 1;
if(ofd.ShowDialog() == DialogResult.OK)
{
txtAddressCount.Text = ("Address count: "+ ofd.FileName);
}
}
private void btnPrintFile_Click(object sender, EventArgs e)
{
try
{
streamToPrint = new StreamReader(ofd.FileName);
try
{
printFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler
(this.pd_PrintPage);
pd.Print();
}
finally
{
streamToPrint.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
For reference I'm using this article from Microsoft作为参考,我正在使用 Microsoft 的这篇文章
https://learn.microsoft.com/en-us/do.net/api/system.drawing.printing.printdocument?redirectedfrom=MSDN&view=do.net-plat-ext-6.0 https://learn.microsoft.com/en-us/do.net/api/system.drawing.printing.printdocument?redirectedfrom=MSDN&view=do.net-plat-ext-6.0
public void openCVSFile(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
...
}
...
private void btnPrintFile_Click(object sender, EventArgs e)
{
try
{
streamToPrint = new StreamReader(ofd.FileName);
^^^
ofd was declared in the other method
Im new to forms in c#我是 c# 中 forms 的新手
This isn't about forms;这与 forms 无关; you can never reach a variable declared inside one method, from another method.. the variable has to be passed from one method to the other, or it has to be declared at a scope that both methods can access.您永远无法从另一个方法访问一个方法内部声明的变量。该变量必须从一个方法传递到另一个方法,或者必须在两个方法都可以访问的 scope 处声明。
Declare your OpenFileDialog under the class
instead:改为在class
下声明您的 OpenFileDialog:
class YourForm: Form{
private OpenFileDialog ofd = new OpenFileDialog();
or drop it onto the form in the designer so it appears in the tray under the form view:或将其拖放到设计器中的表单上,使其出现在表单视图下的托盘中:
And rename it so it is called ofd
by altering the ( Name ) line in the property grid:并重命名它, ofd
通过更改属性网格中的 ( Name ) 行来调用它:
Either of these ways make it accessible to all methods in the class. Doing it the visual way probably makes life easier in terms of setting other properties like the initial folder, file filter etc这些方法中的任何一种都可以使 class 中的所有方法都可以访问它。以可视化方式进行操作可能会使设置其他属性(如初始文件夹、文件过滤器等)的工作变得更轻松
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.