C# 表单:如何打印出使用不同按钮选择的 CSV 文件
C# forms: how do I print out a CSV file which is selected using a different button
目标:直接打印从我的表单应用程序上的另一个按钮选择的 CSV 文件
问题:我不知道如何告诉 amy btnPrintFile_click 方法 FileName 来自 form1.cs
中的另一个方法
任何帮助将不胜感激,我是 c# 中的表单新手
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);
}
}
作为参考,我使用了 Microsoft 的这篇文章
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#
这与表格无关;您永远无法从另一个方法访问一个方法内声明的变量。该变量必须从一个方法传递到另一个方法,或者必须在两个方法都可以访问的范围内声明。
改为在 class
下声明您的 OpenFileDialog:
class YourForm: Form{
private OpenFileDialog ofd = new OpenFileDialog();
或将其拖放到设计器中的表单上,使其显示在表单视图下的托盘中:
并通过更改 属性 网格中的 (Name) 行将其重命名为 ofd
:
这些方法中的任何一种都可以让 class 中的所有方法访问它。以视觉方式进行设置可能会使设置其他属性(如初始文件夹、文件过滤器等)的工作变得更轻松
目标:直接打印从我的表单应用程序上的另一个按钮选择的 CSV 文件
问题:我不知道如何告诉 amy btnPrintFile_click 方法 FileName 来自 form1.cs
中的另一个方法任何帮助将不胜感激,我是 c# 中的表单新手
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);
}
}
作为参考,我使用了 Microsoft 的这篇文章
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#
这与表格无关;您永远无法从另一个方法访问一个方法内声明的变量。该变量必须从一个方法传递到另一个方法,或者必须在两个方法都可以访问的范围内声明。
改为在 class
下声明您的 OpenFileDialog:
class YourForm: Form{
private OpenFileDialog ofd = new OpenFileDialog();
或将其拖放到设计器中的表单上,使其显示在表单视图下的托盘中:
并通过更改 属性 网格中的 (Name) 行将其重命名为 ofd
:
这些方法中的任何一种都可以让 class 中的所有方法访问它。以视觉方式进行设置可能会使设置其他属性(如初始文件夹、文件过滤器等)的工作变得更轻松