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();
Related
I tried to create a little program to convert PDF to a TIF file using ghostscript but unfortunately it results in an error ("null"). Can't figure out why it's failing:
void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "PDF Files|*.pdf";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
strfilename = openFileDialog1.FileName;
}
}
void button2_Click(object sender, EventArgs e)
{
FolderBrowserDialog targetfolder = new FolderBrowserDialog();
if (targetfolder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
folder = targetfolder.SelectedPath;
}
}
void button3_Click(object sender, EventArgs e)
{
const string DLL_64BITS = "gsdll64.dll";
string NomeGhostscriptDLL;
NomeGhostscriptDLL = DLL_64BITS;
GhostscriptVersionInfo gvi = new GhostscriptVersionInfo(NomeGhostscriptDLL);
///var xDpi = 300;
var yDpi = 300;
using (var rasterizer = new GhostscriptRasterizer())
{
byte[] buffer = File.ReadAllBytes(strfilename);
MemoryStream ms = new MemoryStream(buffer);
rasterizer.Open(ms, gvi, true);
int PdfPages = rasterizer.PageCount;
for (int pageNumber = 1; pageNumber < rasterizer.PageCount; pageNumber++)
{
string outputTIFPath = Path.Combine(folder, "00" + pageNumber.ToString() + ".tiff");
Image pdf2TIF = rasterizer.GetPage(yDpi, pageNumber);
MessageBox.Show(outputTIFPath);
pdf2TIF.Save(outputTIFPath, ImageFormat.Tiff);
}
rasterizer.Close();
}
}
The error looks like this
Can anyone help me to sort this out?
try adding this
MyPlaceHolder.Controls.Add(pd2TIF);
below:
Image pdf2TIF = rasterizer.GetPage(yDpi, pageNumber);
I just read that on a different thread. im not 100% sure if it works
I have a problem I currently cannot insert an image created by Zen Barcode framework in PictureBox into Excel.
So far I only manage to save it as a jpeg file but I want to insert the barcode and the QR code generated into Microsoft Excel when I click the button convert to Excel. The only issue I facing now is that after the barcode and the QR code generated but I cannot get it exported out to Microsoft Excel but I can get what is being keyed into the 'textbox' to excel.
public partial class Form1: Form
{
public object SaveFileDialog1 { get; private set; }
// Bitmap qrCodeImage;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Zen.Barcode.Code128BarcodeDraw barcode = Zen.Barcode.BarcodeDrawFactory.Code128WithChecksum;
pictureBox.Image = barcode.Draw(Barcodetxt.Text, 50);
}
private void btnQR_Click(object sender, EventArgs e)
{
Zen.Barcode.CodeQrBarcodeDraw qrcode = Zen.Barcode.BarcodeDrawFactory.CodeQr;
pictureBox1.Image = qrcode.Draw(QRCodetxt.Text, 50);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnexcel_Click(object sender, EventArgs e)
{
string file = "D:/newdoc.xls";
Workbook workbook = new Workbook();
Worksheet worksheet = new Worksheet("Label Pritting ");
worksheet.Cells[1, 3] = new Cell(Barcodetxt.Text);
worksheet.Cells[2, 5] = new Cell(QRCodetxt.Text);
Bitmap bm = default(Bitmap);
bm = new Bitmap(pictureBox1.Width, pictureBox1.Height);
System.Windows.Forms.Clipboard.SetDataObject(bm, false);
//worksheet.Cells[3, 8] = new Cell(pictureBox.Image);
//worksheet.Cells[1, 2] = new Cell(pictureBox.Image);
// worksheet.Cells[1, 3] = new Cell(pictureBox1.Image);
workbook.Worksheets.Add(worksheet); workbook.Save(file);
// open xls file
Workbook book = Workbook.Load(file);
Worksheet sheet = book.Worksheets[0];
// traverse cells
//foreach (Pair, Cell > cell in sheet.Cells)
{
// dgvCells[cell.Left.Right, cell.Left.Left].Value = cell.Right.Value;
}
// traverse rows by Index
for (int rowIndex = sheet.Cells.FirstRowIndex; rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
{
Row row = sheet.Cells.GetRow(rowIndex);
for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
{
Cell cell = row.GetCell(colIndex);
}
}
}
private void pictureBox_Click(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void Saveqrcodebtn_Click(object sender, EventArgs e)
{
string saveFileName;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "jpg";
saveDialog.Filter = "jpeg|*.jpg";
// saveDialog.FileName = saveFileName;
System.IO.MemoryStream ms = new System.IO.MemoryStream();
if (saveDialog.ShowDialog() == DialogResult.OK)
{
try
{
saveFileName = saveDialog.FileName;
pictureBox.Image.Save(saveFileName);
pictureBox1.Image.Save(saveFileName);
MessageBox.Show(saveFileName + " Save Complete", "Complete", MessageBoxButtons.OK);
}
catch
{
MessageBox.Show("Error file is open/in use");
}
pictureBox1.Image = null;
}
}
private void Barcodebtn_Click(object sender, EventArgs e)
{
string saveFileName;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "jpg";
saveDialog.Filter = "jpeg|*.jpg";
// saveDialog.FileName = saveFileName;
System.IO.MemoryStream ms = new System.IO.MemoryStream();
if (saveDialog.ShowDialog() == DialogResult.OK)
{
try
{
saveFileName = saveDialog.FileName;
pictureBox.Image.Save(saveFileName);
pictureBox1.Image.Save(saveFileName);
MessageBox.Show(saveFileName + " Save Complete", "Complete", MessageBoxButtons.OK);
}
catch
{
MessageBox.Show("Error file is open/in use");
}
pictureBox1.Image = null;
}
}
}
This question already has answers here:
File being used by another process after using File.Create()
(11 answers)
Closed 6 years ago.
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.IO;
using Newtonsoft.Json;
namespace Youtube_Player
{
public partial class Authentication : Form
{
public static string AuthenticationApplicationDirectory;
public static string AuthenticationFileName = "Authentication.txt";
StreamWriter w;
public static bool formclosed = false;
static Authentication()
{
AuthenticationApplicationDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "Authentication";
if (!Directory.Exists(AuthenticationApplicationDirectory))
{
Directory.CreateDirectory(AuthenticationApplicationDirectory);
}
AuthenticationFileName = Path.Combine(AuthenticationApplicationDirectory, AuthenticationFileName);
if (!File.Exists(AuthenticationFileName))
File.Create(AuthenticationFileName);
}
public Authentication()
{
InitializeComponent();
cTextBox1.Text = Form1.AuthenticationValues.ApiKey;
cTextBox2.Text = Form1.AuthenticationValues.UserId;
cTextBox3.Text = Form1.AuthenticationValues.JsonFileDirectory;
label1.Visible = false;
button1.Enabled = false;
button4.Enabled = false;
cTextBox2.WaterMarkForeColor = Color.Blue;
cTextBox3.WaterMarkForeColor = Color.Green;
cTextBox2.WaterMarkActiveForeColor = Color.Blue;
cTextBox3.WaterMarkActiveForeColor = Color.Green;
cTextBox1.ForeColor = Color.Red;
cTextBox2.ForeColor = Color.Blue;
cTextBox3.ForeColor = Color.Green;
cTextBox1.WaterMark = "Enter Api Key";
cTextBox2.WaterMark = "Enter Email Account";
cTextBox3.WaterMark = "Browse To The Json File Location";
}
private void Authentication_Load(object sender, EventArgs e)
{
}
private void cTextBox1_TextChanged(object sender, EventArgs e)
{
if (cTextBox1.Text != "Enter Api Key" && cTextBox1.Text != "")
{
button1.Enabled = true;
}
else
{
button1.Enabled = false;
}
}
private void cTextBox2_TextChanged(object sender, EventArgs e)
{
if (cTextBox2.Text != "Enter Email Account" && cTextBox2.Text != "")
{
button4.Enabled = true;
}
else
{
button4.Enabled = false;
}
}
private void cTextBox3_TextChanged(object sender, EventArgs e)
{
if (cTextBox3.Text != "Browse To The Json File Location" && cTextBox3.Text != "")
button6.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Confirmed";
button1.Enabled = false;
label1.Text = "Updating Settings File";
label1.Visible = true;
if (label1.Visible == true)
{
button6.Enabled = false;
button4.Enabled = false;
button1.Enabled = false;
}
FileInfo fi = new FileInfo(AuthenticationFileName);
if (fi.Length == 0)
{
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("Api" + "=" + cTextBox1.Text);
w.Close();
}
else
{
w = new StreamWriter(AuthenticationFileName);
w.WriteLine("Api" + "=" + cTextBox1.Text);
w.Close();
}
timer1.Start();
}
private void button4_Click(object sender, EventArgs e)
{
button4.Enabled = false;
label1.Text = "Updating Settings File";
label1.Visible = true;
if (label1.Visible == true)
{
button6.Enabled = false;
button4.Enabled = false;
button1.Enabled = false;
}
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("UserId" + "=" + cTextBox2.Text);
w.Close();
timer1.Start();
}
private void button6_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Json Files (*.json)|*.json";
openFileDialog1.FilterIndex = 0;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
cTextBox3.BackColor = Color.White;
cTextBox3.ForeColor = Color.Green;
cTextBox3.Text = openFileDialog1.FileName;
label1.Text = "Updating Settings File";
label1.Visible = true;
if (label1.Visible == true)
{
button6.Enabled = false;
button4.Enabled = false;
button1.Enabled = false;
}
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("JsonFileDirectory" + "=" + cTextBox3.Text);
w.Close();
timer1.Start();
}
}
private void button2_Click(object sender, EventArgs e)
{
ResetValues(true);
}
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
count += 1;
if (count == 2)
{
label1.Visible = false;
timer1.Stop();
count = 0;
}
}
private void Authentication_FormClosing(object sender, FormClosingEventArgs e)
{
ResetValues(false);
}
private void ResetValues(bool DeleteFile)
{
cTextBox1.Text = "";
cTextBox2.Text = "";
cTextBox3.Text = "";
button1.Text = "Confirm";
button4.Text = "Confirm";
button6.Enabled = true;
timer1.Stop();
count = 0;
if (DeleteFile == true)
{
if (File.Exists(AuthenticationFileName))
File.Delete(AuthenticationFileName);
}
Form1.AuthenticationValues.ApiKey = "";
Form1.AuthenticationValues.JsonFileDirectory = "";
Form1.AuthenticationValues.UserId = "";
if (Form1.AuthenticationValues.AuthenticationMenu.Enabled
== false && (Form1.lines.Length < 3 && Form1.lines.Length > 0))
Form1.AuthenticationValues.AuthenticationMenu.Enabled = true;
formclosed = true;
}
}
}
The first problem is in the constructor when checking for the file existing:
if (!File.Exists(AuthenticationFileName))
File.Create(AuthenticationFileName);
This make the file to be busy in use. When later in my code i'm trying to use the file again to write to it i'm getting exception that the file is in use by another process.
The second problem is in the 3 places i'm trying to write to the file.
The first place:
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("Api" + "=" + cTextBox1.Text);
w.Close();
Then under it in another place in the code i'm writing again to the file:
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("UserId" + "=" + cTextBox2.Text);
w.Close();
And last:
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("JsonFileDirectory" + "=" + cTextBox3.Text);
w.Close();
The problems are first the file is busy in use since the checking if exist i'm doing in the constructor.
The second problem is that i want to make that if in the file there is no line that start with "Api" then write the Api part:
w.WriteLine("Api" + "=" + cTextBox1.Text);
But if it does exist and the text is changed in the textBox cTextBox1.Text i want to write to the file the changed text to the place where the Api line is. And to append a new Api line.
Same for all two other places i'm writing to the file.
If i will make it all false not to appen when writing it will write one line each time and will overwrite the line.
But if i'm doing true it will append many Api lines or many UserId lines.
And i want each to time to replace the line with the textBox to overwrite only on this line but with the new text.
If in cTextBox1 there is the text: Hello World
Then i changed it to: Hello World Now
Then replace the Api line Hello World with Hello World Now
Alright, addressing your main concern:
File.CreateFile actually opens a filestream for you to use. Easiest way to solve this is to do File.CreateFile().Close() to close it when you're done.
Next, you are trying to change data in a file, but you never read it to find the information.
You can look up StreamReader and use that, and parse out data and figure out what's where, but there's a much more obvious choice: Just re-write all of the information every time.
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.
I need to be able to delete items from a listbox but when I press the delete function and say yes I want to delete I get this exception: Items collection cannot be modified when the DataSource property is set.
Now I want to know what to do about this.
namespace Flashloader
{
public partial class Form1 : Form
{
private controllerinifile _controllerIniFile;
private toepassinginifile _toepassingIniFile;
// private Toepassinglist _toepassingList;
private StringList _comPorts;
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
button4.Visible = false;
_controllerIniFile = new controllerinifile();
_toepassingIniFile = new toepassinginifile(_controllerIniFile.Controllers);
// _toepassingList = new Toepassinglist(_controllerList).FromIniFile();
_comPorts = new StringList();
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
_controllercombobox.DataSource = _controllerIniFile.Controllers;
_applicationListBox.Refresh();
_controllercombobox.Refresh();
Settings settings = _toepassingIniFile.Settings;
textBox3.Text = settings.Port;
textBox4.Text = settings.Baudrate;
}
// File select Button and file directory
private void button2_Click(object sender, EventArgs e)
{
appfile.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
{
if (appfile.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(appfile.FileName);
sr.Close();
}
}
String filedata = appfile.FileName;
appfile.Title = ("Choose a file");
appfile.InitialDirectory = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Application.ExecutablePath), #"C:\\\\Projects\\flashloader2013\\mainapplication\\");
textBox1.Text = string.Format("{0}", appfile.FileName);
}
// textbox for the bootfile
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
// start button for sending appfiles
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
serialPort1.Open();
if (MessageBox.Show(appfile.FileName + " is selected and ready to be send,Are you sure you want to send the selected file?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The selected file will not be send.", "", MessageBoxButtons.OK);
}
else
{
button1.Visible = false;
button4.Visible = true;
}
try
{
using (FileStream inputstream = new FileStream(OpenBoot.FileName, FileMode.Open, FileAccess.Read, FileShare.Read, 32 * 1024 * 1024, FileOptions.SequentialScan))
{
byte[] buffer = new byte[8 * 1024 * 1024];
long bytesRead = 0, streamLength = inputstream.Length;
inputstream.Position = 0;
while (bytesRead < streamLength)
{
long toRead = streamLength - bytesRead;
if (toRead < buffer.Length)
buffer = new byte[(int)toRead];
if (inputstream.Read(buffer, 0, buffer.Length) != buffer.Length)
throw new Exception("File read error");
bytesRead += buffer.Length;
serialPort1.Write(buffer, 0, buffer.Length);
}
}
}
catch
{
MessageBox.Show("No file selected");
}
StringList list = new StringList().FromFile(appfile.FileName);
// Read file and put it in a list that will be sorted.
foreach (String line in list)
{
list.Sort();
serialPort1.Write(line);
}
MessageBox.Show("Bootfile and Applicationfile are send succesfully.");
}
// abort button for sending files
private void button4_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
button4.Visible = false;
button1.Visible = true;
progressBar1.Value = 0;
timer1.Enabled = false;
serialPort1.Close();
}
// backgroundworkers
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
DateTime start = DateTime.Now;
e.Result = "";
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(50);
backgroundWorker1.ReportProgress(i, DateTime.Now);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
}
TimeSpan duration = DateTime.Now - start;
e.Result = "Duration: " + duration.TotalMilliseconds.ToString() + " ms.";
}
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
DateTime time = Convert.ToDateTime(e.UserState);
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("The task has been cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
}
else
{
MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());
}
}
private void Boot_button_Click(object sender, EventArgs e)
{
OpenBoot.Filter = "Binary Files (.BIN; .md6; .md7)|*.BIN; *.md6; *.md7|All Files (*.*)|*.*";
{
if (OpenBoot.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(appfile.FileName);
sr.Close();
}
}
String filedata = OpenBoot.FileName;
OpenBoot.Title = ("Choose a file");
OpenBoot.InitialDirectory = "C:\\Projects\\flashloader2013\\mainapplication\\Bootfiles";
textBox2.Text = string.Format("{0}", OpenBoot.FileName);
}
// Saving the settings to the INI file.
private void SaveSettings()
{
Toepassing toepassing = GetCurrentApplication();
if (toepassing == null)
{
MessageBox.Show("No Application selected");
return;
}
toepassing.Controller = (Controller)_controllercombobox.SelectedItem;
toepassing.Lastfile = textBox1.Text;
// toepassing.TabTip =
_toepassingIniFile.Save();
}
private Controller GetCurrentController()
{
int index = _controllercombobox.SelectedIndex;
if (index < 0)
return null;
return _controllerIniFile.Controllers[index];
}
private Toepassing GetCurrentApplication()
{
int index = _applicationListBox.SelectedIndex;
if (index < 0)
return null;
return _toepassingIniFile.ToePassingen[index];
}
private void typelistbox_SelectedIndexChanged(object sender, EventArgs e)
{
Toepassing toepassing = GetCurrentApplication();
if (toepassing == null)
{
// TODO velden leegmaken
}
else
{
// appfile.InitialDirectory = Path.GetDirectoryName(controller.Lastfile);
appfile.FileName = toepassing.Lastfile;
textBox1.Text = toepassing.Lastfile;
_controllercombobox.SelectedItem = toepassing.Controller;
}
}
private void _controllercombobox_SelectedIndexChanged(object sender, EventArgs e)
{
Controller controller = GetCurrentController();
if (controller == null)
{
// TODO velden leegmaken
}
else
{
textBox2.Text = controller.Bootfile;
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void changeCurrentControllerToolStripMenuItem_Click(object sender, EventArgs e)
{
var controlleredit = new Controlleredit(_controllerIniFile);
controlleredit.Show();
Refresh();
}
private void addControllerToolStripMenuItem_Click(object sender, EventArgs e)
{
var controllersettings = new Newcontroller(_controllerIniFile);
controllersettings.ShowDialog();
_controllercombobox.DataSource = null;
_controllercombobox.DataSource = _controllerIniFile.Controllers;
// Refresh();
// _controllercombobox.Refresh();
}
private void newapplicationBtton_Click(object sender, EventArgs e)
{
var newapplication = new NewApplication(_toepassingIniFile);
newapplication.ShowDialog();
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
}
/////////////////////////////The Error is down here /////////////////////////////
private void button3_Click(object sender, EventArgs e)
{
if (MessageBox.Show("You are about to delete application: "+ Environment.NewLine + _applicationListBox.SelectedItem +Environment.NewLine + " Are you sure you want to delete the application?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The application will not be deleted.", "", MessageBoxButtons.OK);
}
else if (this._applicationListBox.SelectedIndex >= 0)
this._applicationListBox.Items.RemoveAt(this._applicationListBox.SelectedIndex);
}
}
}
The error says it quite clearly: you have to remove the item from the underlying datasource, you can't delete it manually. If you want to remove/add items manually, you shouldn't use databinding but build the list by hand.
As exception say you can't delete items directly from ListBox - you have to remove it from underlying DataSource and then rebind control (if it is not bound to BindingSource for example)
private void button3_Click(object sender, EventArgs e)
{
if (MessageBox.Show("You are about to delete application: "+ Environment.NewLine + _applicationListBox.SelectedItem +Environment.NewLine + " Are you sure you want to delete the application?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The application will not be deleted.", "", MessageBoxButtons.OK);
}
else if (this._applicationListBox.SelectedIndex >= 0)
{
var item = this.GetCurrentApplication();
_toepassingIniFile.ToePassingen.Remove(item);
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
}
}
Your code is hard to read so I was a bit guessing with classes etc, but it should work.
Try to remove from datasource itself as below:
string myobj = this._applicationListBox.SelectedValue.ToString();
data.Remove(myobj );
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = data;
As others have said. You must have a list that is bound to the listbox. You cannot delete from the listbox directly.
You should delete from the List
private Toepassinglist _toepassingList
That is the datasource for your listbox.
Delete the item you want like so...
this._toepassingList.Items.RemoveAt(this._applicationListBox.SelectedIndex);
You can delete from list:---
ListName.Items.RemoveAt(postion);