Save file dialog An unhandled exception - c#

I have some problems about savefiledialog c#, I have an unhandled exception of type System.NullReferenceException when I debug, this's code:
private void saveToolStripMenuItem_Click(object sender, System.EventArgs e)
{
switch (fileName)
{
case "":
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
fileName = saveFileDialog1.FileName;
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
break;
default:
{
bitmap.Save(fileName, ImageFormat.Bmp);
}
break;
}
}
here is my declare:
private string fileName = "";
private Bitmap bitmap;
private Bitmap curBitmap;
here is my full code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Bitmap
//Graphics
Graphics g;
Pen p = new Pen(Color.Black, 8);
Point start = new Point(0, 0);
Point end = new Point(0, 0);
bool drawing = false;
//private int x1;
//private int x2;
//private int y1;
//private int y2;
//private int d1;
//private int d2;
private string fileName = "";
private Bitmap bitmap;
private Bitmap curBitmap;
private Size fullSize;
private void btnColorPicker_Click(object sender, EventArgs e)
{
//Get colors from colordialog
DialogResult r = colorDialog1.ShowDialog();
if (r == DialogResult.OK)
{
p.Color = colorDialog1.Color;
}
}
private void PanelDrawing_MouseUp(object sender, MouseEventArgs e)
{
drawing = false;
}
private void PanelDrawing_MouseMove(object sender, MouseEventArgs e)
{
if (drawing && !earaser)
{
p.Width = PenSize.Value;
p.Color = colorDialog1.Color;
end = e.Location;
g = PanelDrawing.CreateGraphics();
g.DrawLine(p, start, end);
PanelDrawing.Cursor = Cursors.HSplit;
}
else if (drawing && earaser)
{
end = e.Location;
g = PanelDrawing.CreateGraphics();
g.DrawLine(p, start, end);
PanelDrawing.Cursor = Cursors.Cross;
}
else if (!drawing)
{
PanelDrawing.Cursor = Cursors.Default;
}
start = end;
}
private void PanelDrawing_MouseDown(object sender, MouseEventArgs e)
{
start = e.Location;
if (e.Button == MouseButtons.Left)
{
drawing = true;
}
}
private void PenSize_Scroll(object sender, EventArgs e)
{
p.Width = PenSize.Value;
label1.Text = "" + PenSize.Value;
}
bool earaser = false;
private void btnEaraser_Click(object sender, EventArgs e)
{
p.Color = Color.White;
p.Width = 10;
earaser = true;
}
private void btnBrush_Click(object sender, EventArgs e)
{
earaser = false;
}
private void btnClear_Click(object sender, EventArgs e)
{
g.Clear(PanelDrawing.BackColor);
}
private void saveToolStripMenuItem_Click(object sender, System.EventArgs e)
{
if (string.IsNullOrWhiteSpace(fileName))
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
return;
fileName = saveFileDialog1.FileName;
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
else
{
bitmap.Save(fileName, ImageFormat.Bmp);
}
}
private void Form1_Load(object sender, EventArgs e)
{
fullSize = SystemInformation.PrimaryMonitorMaximizedWindowSize;
bitmap = new Bitmap(fullSize.Width, fullSize.Height);
g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(BackColor);
}
}

probably it didn't catch the variable if its null or an empty string.
so instead of using switch statement, try doing it in If-Else statement.

This isn't the place to use a switch statement. This is much easier re-written as an if:
private void saveToolStripMenuItem_Click(object sender, System.EventArgs e)
{
if (string.IsNullOrWhiteSpace(fileName))
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
return;
fileName = saveFileDialog1.FileName;
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
else
{
bitmap.Save(fileName, ImageFormat.Bmp);
}
}
The switch isn't appropriate just because its extremely confusing, and you have to test for multiple cases (null, empty string, whitespace). You can jam the code and make it work, but this is a lot more fool-proof.
Without seeing the rest of your code, its impossible to tell whether bitmap is going to be null or not. If its null, then calling .Save will result in a NullReferenceException. The best way to know why its null is to learn how to use the debugger. Set a breakpoint at the bitmap or where you utilize the bitmap to see why you aren't writing to it or creating the object in the first place.

Since you haven't specified "where" the System.NullReferenceException is taking place. I will assume the following 2 cases
1.fileName is null. If that's the case add 1 more case (as shown below ) to your switch statement that takes null into consideration.
switch (fileName)
{
case "":
case null:
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
fileName = saveFileDialog1.FileName;
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
break;
default:
{
bitmap.Save(fileName, ImageFormat.Bmp);
}
break;
}
2. You are using the same image stream, while saving, which was used to construct it. If that's the case use a new bitmap object as shown below.
var newBitmap = new Bitmap(bitmap);
switch (fileName)
{
case "":
case null:
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
fileName = saveFileDialog1.FileName;
newBitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
break;
default:
{
newBitmap.Save(fileName, ImageFormat.Bmp);
}
break;
}

Firstly, switch is not good way to handle strings I think.
string.IsNullorEmpty and string.IsNullorWhiteSpace might be useful for you.
Can you trace bitmap on your console? Are you sure you declared and initialized it correctly in your code?
This should solve any possibility:
private void saveToolStripMenuItem_Click(object sender,System.EventArgs e)
{
var _Bitmap = new Bitmap(bitmap);
//when we quit here we don't need this anymore; declaring it here helps with memory management
if(_Bitmap == null)
return;
if(string.IsNullorEmpty(fileName)||string.IsNullorWhiteSpace(fileName)
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
}
else
{
_Bitmap.Save(fileName,ImageFormat.Bmp);
}
}
You assign bitmap on Form1_Load, try to do it on separate method and call it when you need it.

Related

how to load cropping image to picturebox c#

Here is my small software.. We add images clicking "ADD YOUR QR CODE" and it will be displayed on pictureBoxLoad picturebox, After that i will crop the image. Then it shows on picturebox2.
But my problem is ,it is only shows on picturebox2, But picturebox2.image is null...how to fix that error. I want to add cropping image to picturebox2 without null..
here after clicking the crop button
here is the code i tried
{
int xDown = 0;
int yDown = 0;
int xUp = 0;
int yUp = 0;
Rectangle rectCropArea = new Rectangle();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Task timeout;
string fn = "";
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
}
private void selectIm_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
if (opf.ShowDialog() == DialogResult.OK)
{
PictureBoxLoad.Image = Image.FromFile(opf.FileName);
fn = opf.FileName;
}
PictureBoxLoad.Cursor = Cursors.Cross;
}
private void PictureBoxLoad_MouseUp(object sender, MouseEventArgs e)
{
}
private void PictureBoxLoad_MouseDown(object sender, MouseEventArgs e)
{
}
private void crop_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
opf.Filter= "Image Files(*.jpg; *.jpeg; *.gif;*.png; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp;*.png";
if (opf.ShowDialog() == DialogResult.OK)
{
PictureBoxLoad.Image = Image.FromFile(opf.FileName);
fn = opf.FileName;
}
PictureBoxLoad.Cursor = Cursors.Cross;
}
private void button2_Click(object sender, EventArgs e)
{
string root = #"C:\FuePass";
// If directory does not exist, create it.
if (!System.IO.Directory.Exists(root))
{
System.IO.Directory.CreateDirectory(root);
}
Bitmap bmp = new Bitmap(previewimg.Width, previewimg.Height);
previewimg.DrawToBitmap(bmp, new Rectangle(0, 0, previewimg.Width, previewimg.Height));
pictureBox2.DrawToBitmap(bmp, new Rectangle(pictureBox2.Location.X - previewimg.Location.X, pictureBox2.Location.Y - previewimg.Location.Y, pictureBox2.Width, pictureBox2.Height));
bmp.Save(#"C:\Fuepass\output.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
MessageBox.Show("Saved,Locaiton : C:\\Fuepass\\");
// SaveFileDialog dialog = new SaveFileDialog();
// dialog.Filter = "JPG(*.JPG)|*.jpg";
// if (dialog.ShowDialog() == DialogResult.OK)
// {
// previewimg.Image.Save(dialog.FileName);
// pictureBox2.Image.Save(dialog.FileName);
// }
// }
}
private void PictureBoxLoad_Click(object sender, EventArgs e)
{
}
private void PictureBoxLoad_MouseDown_1(object sender, MouseEventArgs e)
{
PictureBoxLoad.Invalidate();
xDown = e.X;
yDown = e.Y;
crop.Enabled = true;
}
private void PictureBoxLoad_MouseUp_1(object sender, MouseEventArgs e)
{
//pictureBox1.Image.Clone();
xUp = e.X;
yUp = e.Y;
Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
using (Pen pen = new Pen(Color.YellowGreen, 3))
{
PictureBoxLoad.CreateGraphics().DrawRectangle(pen, rec);
}
rectCropArea = rec;
crop.Enabled = true;
}
private void crop_Click_1(object sender, EventArgs e)
{
try
{
pictureBox2.Refresh();
//Prepare a new Bitmap on which the cropped image will be drawn
Bitmap sourceBitmap = new Bitmap(PictureBoxLoad.Image, PictureBoxLoad.Width, PictureBoxLoad.Height);
Graphics g = pictureBox2.CreateGraphics();
//Draw the image on the Graphics object with the new dimesions
g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
sourceBitmap.Dispose();
crop.Enabled = false;
var path = Environment.CurrentDirectory.ToString();
ms = new System.IO.MemoryStream();
//pictureBox2.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] ar = new byte[ms.Length];
var timeout = ms.WriteAsync(ar, 0, ar.Length);
}
catch (Exception ex)
{
}
if (pictureBox2.Image == null)
{
MessageBox.Show("no image");
}
}
}
}
plz tell me the error
You should be able to set the Image to a Bitmap. But do not dispose the Bitmap before you do the save. Hope this helps.
private void crop_Click_1(object sender, EventArgs e)
{
try
{
pictureBox2.Refresh();
//Prepare a new Bitmap on which the cropped image will be drawn
Bitmap sourceBitmap = new Bitmap(PictureBoxLoad.Image, PictureBoxLoad.Width, PictureBoxLoad.Height);
Graphics g = pictureBox2.CreateGraphics();
//Draw the image on the Graphics object with the new dimesions
g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
crop.Enabled = false;
var path = Environment.CurrentDirectory.ToString();
ms = new System.IO.MemoryStream();
pictureBox2.Image = sourceBitmap;
pictureBox2.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] ar = new byte[ms.Length];
var timeout = ms.WriteAsync(ar, 0, ar.Length);
sourceBitmap.Dispose();
}
catch (Exception ex)
{
}
if (pictureBox2.Image == null)
{
MessageBox.Show("no image");
}
}

How to get the picturebox image path that captured by the webcam

In my form. I have two picturebox and a button that capture the image into picturebox.
Two Picturebox
WebcamImage - represent the live camera image
PreviewImage - represent the Captured image from webcamimage
When i saved this captured image it will go to my UserImage picturebox (In my Usercontrol)
The problems is i don't know how i'm gonna get the picturebox image path.
What i want is when i click my saved button the image path will be saved to my label text.
Here's my code
PS: I'm using Aforge.dll
public partial class CaptureImage : Form
{
private FilterInfoCollection CaptureDevice;
private VideoCaptureDevice FinalFrame;
RegisterCustomer _view;
public CaptureImage(RegisterCustomer view)
{
InitializeComponent();
this._view = view;
}
private void CaptureImage_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0;
FinalFrame = new VideoCaptureDevice();
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);
if (FinalFrame.VideoCapabilities.Length > 0)
{
string highestSolution = "0;0";
//Search for the highest resolution
for (int i = 0; i < FinalFrame.VideoCapabilities.Length; i++)
{
if (FinalFrame.VideoCapabilities[i].FrameSize.Width > Convert.ToInt32(highestSolution.Split(';')[0]))
highestSolution = FinalFrame.VideoCapabilities[i].FrameSize.Width.ToString() + ";" + i.ToString();
}
}
FinalFrame.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
btn_save.Hide();
btn_cancel.Hide();
}
void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
WebcamImage.Image = (Bitmap)eventArgs.Frame.Clone();
}
private void CaptureImage_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalFrame.IsRunning == true)
{
FinalFrame.Stop();
}
}
private void btn_save_Click(object sender, EventArgs e)
{
_view.UserImage.Image = PreviewImage.Image;
this.Close();
}
private void btn_cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btn_capture_Click(object sender, EventArgs e)
{
PreviewImage.Image = (Bitmap)WebcamImage.Image.Clone();
PreviewImage.BringToFront();
btn_capture.Hide();
btn_save.Show();
btn_cancel.Show();
}
}
This is only i know in getting the picturebox image path by using openfile dialog
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Image Files (*.jpg;*.jpeg;.*.png; | *.jpg;*.jpeg;.*.png;)";
ofd.FilterIndex = 1;
ofd.Multiselect = false;
ofd.Title = "Select Image File";
if (ofd.ShowDialog() == DialogResult.OK)
{
location = ofd.FileName;
path.Text = location;
UserImage.Image = Image.FromFile(location);
UserImage.SizeMode = PictureBoxSizeMode.StretchImage;
}
}

To clear loaded images in a picturebox-c#

Initially I will be loading images(say 20 images) into a picturebox from a specified folder through selection from combobox dropdown, they get loaded normally into the picturebox.
The problem I am facing is when I select the next folder to acquire the image for processing, the previously selected folders images are also displayed in the picturebox after its count only the next folders images are displayed, I am unable to clear the previously loaded images.
To be specific, when I click on a folder from dropdown I want the particular folders image inside the picturebox I don't want the previously loaded images along with them. Am working in VS2013 with c#.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
ArrayList alist = new ArrayList();
int i = 0;
int filelength = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo di = new DirectoryInfo(#"C:\Users\Arun\Desktop\scanned");
DirectoryInfo[] folders = di.GetDirectories();
comboBox1.DataSource = folders;
}
private void button7_Click(object sender, EventArgs e)
{
if (i + 1 < filelength)
{
pictureBox1.Image = Image.FromFile(alist[i + 1].ToString());
i = i + 1;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
private void button8_Click(object sender, EventArgs e)
{
if (i - 1 >= 0)
{
pictureBox1.Image = Image.FromFile(alist[i - 1].ToString());
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
i = i - 1;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = comboBox1.SelectedItem.ToString();
String fullpath = Path.Combine(#"C:\Users\Arun\Desktop\scanned", selected);
DirectoryInfo di1 = new DirectoryInfo(fullpath);
DirectoryInfo[] folders1 = di1.GetDirectories();
comboBox2.DataSource = folders1;
}
private void button9_Click(object sender, EventArgs e)
{
string selected1 = comboBox1.SelectedItem.ToString();
string selected2 = comboBox2.SelectedItem.ToString();
//Initially load all your image files into the array list when form load first time
System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(Path.Combine(#"C:\Users\Arun\Desktop\scanned", selected1, selected2)); //Source image folder path
try
{
if ((inputDir.Exists))
{
//Get Each files
System.IO.FileInfo file = null;
foreach (System.IO.FileInfo eachfile in inputDir.GetFiles())
{
file = eachfile;
if (file.Extension == ".tif")
{
alist.Add(file.FullName); //Add it in array list
filelength = filelength + 1;
}
else if(file.Extension == ".jpg")
{
alist.Add(file.FullName); //Add it in array list
filelength = filelength + 1;
}
}
pictureBox1.Image = Image.FromFile(alist[0].ToString()); //Display intially first image in picture box as sero index file path
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
i = 0;
}
}
catch (Exception ex)
{
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.D)
{
if (i + 1 < filelength)
{
pictureBox1.Image = Image.FromFile(alist[i + 1].ToString());
i = i + 1;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
else if(e.KeyCode == Keys.A)
{
if (i - 1 >= 0)
{
pictureBox1.Image = Image.FromFile(alist[i - 1].ToString());
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
i = i - 1;
}
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Your code has many issues.
The one you are looking for is that you don't clear the alist before loading new file names.
So insert:
alist.Clear();
before
//Get Each files
And also
filelength = alist.Count;
after the loop. No need to count while adding!
Also note that ArrayList is pretty much depracated and you should use the type-safe and powerful List<T> instead:
List<string> alist = new List<string>();
Of course a class variable named i is silly and you are also relying on always having a SelectedItem in the comboBox2.
And since you are not properly Disposing of the Image you are leaking GDI resources.
You can use this function for properly loading images:
void loadImage(PictureBox pbox, string file)
{
if (pbox.Image != null)
{
var dummy = pbox.Image;
pbox.Image = null;
dummy.Dispose();
}
if (File.Exists(file)) pbox.Image = Image.FromFile(file);
}
It first creates a reference to the Image, then clears the PictureBox's reference, then uses the reference to Dispose of the Image and finally tries to load the new one.

Audio playing stopped when i resize a WaveForm to form size

I have a problem with my audio application. I'm using nAudio library.
So when I play a sound without using "SamplesPerPixel" method on my waveViewer control, everything works perfectly, but when I want assign a value to this method. The Sound, when I play it starts from unexpected time and finish about 4sec. later.
Here is my code:
namespace AudioMixer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int bytesPerSample;
int samples;
int samplespixel;
private NAudio.Wave.WaveStream pcm = null;
private NAudio.Wave.BlockAlignReductionStream stream = null;
private NAudio.Wave.DirectSoundOut output = null;
private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Audio File (*.wav;*.mp3)|*.wav;*.mp3;";
if (dialog.ShowDialog() != DialogResult.OK) return;
DisposeWave();
if (dialog.FileName.EndsWith(".mp3"))
{
pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(dialog.FileName));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
else if (dialog.FileName.EndsWith(".wav"))
{
pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(dialog.FileName));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
output = new NAudio.Wave.DirectSoundOut();
output.Init(stream);
output.Stop();
waveViewer1.WaveStream = stream;
bytesPerSample = (pcm.WaveFormat.BitsPerSample / 8) * pcm.WaveFormat.Channels;
samples = (int)(pcm.Length / bytesPerSample);
samplespixel = samples / this.Width;
waveViewer1.SamplesPerPixel = samplespixel;
opened_file_name.Text = dialog.FileName;
play_button.Visible = true;
play_button.Enabled = true;
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
waveViewer1.SamplesPerPixel = samplespixel;
}
private void Form1_Load(object sender, EventArgs e)
{
opened_file_name.Text = "Audio file not opened, choose one from Your computer";
play_button.Visible = false;
}
private void play_button_Click(object sender, EventArgs e)
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Pause();
}
else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
{
output.Play();
}
else if (output.PlaybackState == NAudio.Wave.PlaybackState.Stopped)
{
output.Play();
}
}
}
private void DisposeWave()
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Stop();
output.Dispose();
output = null;
}
}
if (stream != null)
{
stream.Dispose();
stream = null;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DisposeWave();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
i think this may help you
waveViewer1.SamplesPerPixel = 400;
waveViewer1.StartPosition = 400;

How to print a Windows Form

I have made an Address Book WinForm in C# and would like to know how to print it as a text file, how would I go about doing this?
I have displayed everything in a DataGridView, I would ideally just like to print the information in the table as text.
you can try like this...
[STAThread]
static void Main()
{
Application.Run(new PrintPreviewDialog());
}
private void btnOpenFile_Click(object sender, System.EventArgs e)
{
openFileDialog.InitialDirectory = #"c:\";
openFileDialog.Filter = "Text files (*.txt)|*.txt|" +
"All files (*.*)|*.*";
openFileDialog.FilterIndex = 1; // 1 based index
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
StreamReader reader = new StreamReader(openFileDialog.FileName);
try
{
strFileName = openFileDialog.FileName;
txtFile.Text = reader.ReadToEnd();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
finally
{
reader.Close();
}
}
}
private void btnSaveFile_Click(object sender, System.EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = #"c:\";
sfd.Filter = "Text files (*.txt)|*.txt|" +
"All files (*.*)|*.*";
sfd.FilterIndex = 1; // 1 based index
if (strFileName != null)
sfd.FileName = strFileName;
else
sfd.FileName = "*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(strFileName,false);
try
{
strFileName = sfd.FileName;
writer.Write(txtFile.Text);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
finally
{
writer.Close();
}
}
}
//here you can print form as text file by clicking on the button..
private void btnPageSetup_Click(object sender, System.EventArgs e)
{
PageSetupDialog psd = new PageSetupDialog();
psd.Document = printDocument;
psd.ShowDialog();
}
private void btnPrint_Click(object sender, System.EventArgs e)
{
PrintDialog pdlg = new PrintDialog();
pdlg.Document = printDocument;
if (pdlg.ShowDialog() == DialogResult.OK)
{
try
{
printDocument.Print();
}
catch(Exception ex)
{
MessageBox.Show("Print error: " + ex.Message);
}
}
}
private void btnPrintPreview_Click(object sender, System.EventArgs e)
{
PrintPreviewDialog ppdlg = new PrintPreviewDialog();
ppdlg.Document = printDocument;
ppdlg.ShowDialog();
}
private void pdPrintPage(object sender, PrintPageEventArgs e)
{
float linesPerPage = 0;
float verticalOffset = 0;
float leftMargin = e.MarginBounds.Left;
float topMargin = e.MarginBounds.Top;
int linesPrinted = 0;
String strLine = null;
linesPerPage = e.MarginBounds.Height / currentFont.GetHeight(e.Graphics);
while (linesPrinted < linesPerPage &&
((strLine = stringReader.ReadLine())!= null ))
{
verticalOffset = topMargin + (linesPrinted * currentFont.GetHeight(e.Graphics));
e.Graphics.DrawString(strLine, currentFont, Brushes.Black, leftMargin, verticalOffset);
linesPrinted++;
}
if (strLine != null)
e.HasMorePages = true;
else
e.HasMorePages = false;
}
private void pdBeginPrint(object sender, PrintEventArgs e)
{
stringReader = new StringReader(txtFile.Text);
currentFont = txtFile.Font;
}
private void pdEndPrint(object sender, PrintEventArgs e)
{
stringReader.Close();
MessageBox.Show("Done printing.");
}
}
Preview and Print from Your Windows Forms App with the .NET Printing Namespace
http://msdn.microsoft.com/en-us/magazine/cc188767.aspx
It's a little old (2003) but still looks relevent.
you should give more details on what you want to do.
how do you intend to print the form as text file? How do you convert the graphics like labels, buttons and other controls into text?
what you ask is possible and you can control every aspect of the printed content in both ways graphic rendering or text only, have a look here as starting point:
Windows Forms Print Support
The simpliest way is to create a text file and write the values in it. Like this:
var textFile = File.CreateText("Address.txt");
textFile.WriteLine("Name: Fischermaen");
textFile.Close();

Categories

Resources