How to Print images on paper using PrintDocument - c#

My problem is that is that my code prints the images overlapping each other. I do not know how to change the x and y positions. The printer should print 3 images per row and then move to the next row.
private void panel1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
for (int serial = 0; serial < SaveBeforePrint.Count; serial++)
{
String intercharacterGap = "0";
String str = '*' + SaveBeforePrint[serial].ToUpper() + '*';
int strLength = str.Length;
for (int i = 0; i < SaveBeforePrint[serial].Length; i++)
{
string barcodestring = SaveBeforePrint[serial].ToUpper();
if (alphabet39.IndexOf(barcodestring[i]) == -1 || barcodestring[i] == '*')
{
e.Graphics.DrawString("INVALID BAR CODE TEXT", Font, Brushes.Red, 10, 10);
return;
}
}
String encodedString = "";
for (int i = 0; i < strLength; i++)
{
if (i > 0)
encodedString += intercharacterGap;
encodedString += coded39Char[alphabet39.IndexOf(str[i])];
}
int encodedStringLength = encodedString.Length;
int widthOfBarCodeString = 0;
double wideToNarrowRatio = 3;
if (align != AlignType.Left)
{
for (int i = 0; i < encodedStringLength; i++)
{
if (encodedString[i] == '1')
widthOfBarCodeString += (int)(wideToNarrowRatio * (int)weight);
else
widthOfBarCodeString += (int)weight;
}
}
int x = 0;
int wid = 0;
int yTop = 0;
SizeF hSize = e.Graphics.MeasureString(headerText, headerFont);
SizeF fSize = e.Graphics.MeasureString(code, footerFont);
int headerX = 0;
int footerX = 0;
int printonpage = 0;
if (align == AlignType.Left)
{
x = leftMargin;
headerX = leftMargin;
footerX = leftMargin;
}
else if (align == AlignType.Center)
{
x = (Width - widthOfBarCodeString) / 2;
headerX = (Width - (int)hSize.Width) / 2;
footerX = (Width - (int)fSize.Width) / 2;
}
else
{
x = Width - widthOfBarCodeString - leftMargin;
headerX = Width - (int)hSize.Width - leftMargin;
footerX = Width - (int)fSize.Width - leftMargin;
}
if (showHeader)
{
yTop = (int)hSize.Height + topMargin;
e.Graphics.DrawString(headerText, headerFont, Brushes.Black, headerX, topMargin);
}
else
{
yTop = topMargin;
}
for (int i = 0; i < encodedStringLength; i++)
{
if (encodedString[i] == '1')
wid = (int)(wideToNarrowRatio * (int)weight);
else
wid = (int)weight;
e.Graphics.FillRectangle(i % 2 == 0 ? Brushes.Black : Brushes.White, x, yTop, wid, height);
x += wid;
}
yTop += height;
if (showFooter)
e.Graphics.DrawString(SaveBeforePrint[serial], footerFont, Brushes.Black, footerX, yTop);
}
}
Desired output :
I am getting :
As you can see the last digit is overlapping. I want to draw it next to the previous one

I have observed the code and found the issue.. in panel1_print u are not incrementing the values properly..
I have made the required changes now u will get the 4 bar in a line and 5th one in another line - check the attached image.
just replace ur panel1_Paint with this new code thats it you can find the changes..
I have marked them as
//start changes by Deepak
..
..
..
//end changes by Deepak
and also declare two variables loopValX and loopValY as int
here is the code..
private void panel1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
int loopValX = 0;
int loopValY = -150;
for (int serial = 0; serial < SaveBeforePrint.Count; serial++)
{
String intercharacterGap = "0";
String str = '*' + SaveBeforePrint[serial].ToUpper() + '*';
int strLength = str.Length;
for (int i = 0; i < SaveBeforePrint[serial].Length; i++)
{
string barcodestring = SaveBeforePrint[serial].ToUpper();
if (alphabet39.IndexOf(barcodestring[i]) == -1 || barcodestring[i] == '*')
{
e.Graphics.DrawString("INVALID BAR CODE TEXT", Font, Brushes.Red, 10, 10);
return;
}
}
String encodedString = "";
for (int i = 0; i < strLength; i++)
{
if (i > 0)
encodedString += intercharacterGap;
encodedString += coded39Char[alphabet39.IndexOf(str[i])];
}
int encodedStringLength = encodedString.Length;
int widthOfBarCodeString = 0;
double wideToNarrowRatio = 3;
if (align != AlignType.Left)
{
for (int i = 0; i < encodedStringLength; i++)
{
if (encodedString[i] == '1')
widthOfBarCodeString += (int)(wideToNarrowRatio * (int)weight);
else
widthOfBarCodeString += (int)weight;
}
}
SizeF hSize = e.Graphics.MeasureString(headerText, headerFont);
SizeF fSize = e.Graphics.MeasureString(SaveBeforePrint[serial], footerFont);
int headerX = 0;
int footerX = 0;
if (align == AlignType.Left)
{
x = leftMargin;
headerX = leftMargin;
footerX = leftMargin;
}
else if (align == AlignType.Center)
{
x = (Width - widthOfBarCodeString) / 2;
headerX = (Width - (int)hSize.Width) / 2;
footerX = (Width - (int)fSize.Width) / 2;
}
else
{
x = Width - widthOfBarCodeString - leftMargin;
headerX = Width - (int)hSize.Width - leftMargin;
footerX = Width - (int)fSize.Width - leftMargin;
}
if (showHeader)
{
y = (int)hSize.Height + topMargin;
e.Graphics.DrawString(headerText, headerFont, Brushes.Black, headerX, topMargin);
}
else
{
y = topMargin;
}
//start changes by Deepak
if (serial % 4 == 0)
{
loopValX = 0;
loopValY += 150;
}
else
{
loopValX += 150;
}
x += loopValX;
y += loopValY;
footerX += loopValX;
//end changes by Deepak
for (int i = 0; i < encodedStringLength; i++)
{
if (encodedString[i] == '1')
wid = (int)(wideToNarrowRatio * (int)weight);
else
wid = (int)weight;
e.Graphics.FillRectangle(i % 2 == 0 ? Brushes.Black : Brushes.White, x, y, wid, height);
x += wid;
}
y += height;
if (showFooter)
e.Graphics.DrawString(SaveBeforePrint[serial], footerFont, Brushes.Black, footerX, y);
}
}

You Should do it with the help of a DataGridView (That Contains Images in a Column).
The Images Will Then Print in each new row or column (by modifying as your desire)
The Following Class will do your work by passing it the whole DataGridView And Header in its constructor.
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Linq;
namespace Waqas
{
internal class ClsPrint
{
#region Variables
private int iCellHeight = 0; //Used to get/set the datagridview cell height
private int iTotalWidth = 0; //
private int iRow = 0; //Used as counter
private bool bFirstPage = false; //Used to check whether we are printing first page
private bool bNewPage = false; // Used to check whether we are printing a new page
private int iHeaderHeight = 0; //Used for the header height
private StringFormat strFormat; //Used to format the grid rows.
private ArrayList arrColumnLefts = new ArrayList(); //Used to save left coordinates of columns
private ArrayList arrColumnWidths = new ArrayList(); //Used to save column widths
private PrintDocument _printDocument = new PrintDocument();
private DataGridView gw = new DataGridView();
private string _ReportHeader;
#endregion
public ClsPrint(DataGridView gridview, string ReportHeader)
{
_printDocument.DefaultPageSettings.Landscape = true;
_printDocument.DefaultPageSettings.PaperSize.RawKind = (int)PaperKind.A4;
_printDocument.DefaultPageSettings.Margins = new Margins(30, 30, 30, 30);
//_printDocument.DefaultPageSettings.PaperSize.PaperName = "A4";
_printDocument.PrintPage += new PrintPageEventHandler(_printDocument_PrintPage);
_printDocument.BeginPrint += new PrintEventHandler(_printDocument_BeginPrint);
gw = gridview;
_ReportHeader = ReportHeader;
}
public void PrintForm()
{
//Open the print preview dialog
PrintPreviewDialog objPPdialog = new PrintPreviewDialog();
objPPdialog.Document = _printDocument;
objPPdialog.ShowIcon = false;
objPPdialog.Text = "Print Preview";
objPPdialog.WindowState = FormWindowState.Maximized;
objPPdialog.ShowDialog();
}
private void _printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
//try
//{
//Set the left margin
int iLeftMargin = e.MarginBounds.Left;
//Set the top margin
int iTopMargin = e.MarginBounds.Top;
//Whether more pages have to print or not
bool bMorePagesToPrint = false;
int iTmpWidth = 0;
//For the first page to print set the cell width and header height
if (bFirstPage)
{
foreach (DataGridViewColumn GridCol in gw.Columns)
{
iTmpWidth = ((int) (Math.Floor((double) ((double) GridCol.Width/
(double) iTotalWidth*(double) iTotalWidth*
((double) e.MarginBounds.Width/(double) iTotalWidth)))));
iHeaderHeight = (int) (e.Graphics.MeasureString(GridCol.HeaderText,
GridCol.InheritedStyle.Font, iTmpWidth).Height) + 60;
// Save width and height of headers
arrColumnLefts.Add(iLeftMargin);
arrColumnWidths.Add(iTmpWidth);
iLeftMargin += iTmpWidth;
}
}
//Loop till all the grid rows not get printed
while (iRow <= gw.Rows.Count - 1)
{
DataGridViewRow GridRow = gw.Rows[iRow];
//Set the cell height
iCellHeight = GridRow.Height + 30;
int iCount = 0;
//Check whether the current page settings allows more rows to print
if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
{
bNewPage = true;
bFirstPage = false;
bMorePagesToPrint = true;
break;
}
else
{
if (bNewPage)
{
//Draw Header
e.Graphics.DrawString(_ReportHeader,
new Font("Calibri Light", 20, FontStyle.Bold),
new SolidBrush(Color.Black), e.MarginBounds.Left,
e.MarginBounds.Top+20 - e.Graphics.MeasureString(_ReportHeader,
new Font(gw.Font, FontStyle.Bold),
e.MarginBounds.Width).Height - 13);
String strDate = DateTime.Now.ToString("dd-MMM-yy hh:mm tt");
//Draw Date
e.Graphics.DrawString(strDate,
new Font("Calibri Light", 12, FontStyle.Bold), Brushes.Black,
e.MarginBounds.Left-20 +
(e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
new Font(gw.Font, FontStyle.Bold),
e.MarginBounds.Width).Width),
e.MarginBounds.Top+30 - e.Graphics.MeasureString(_ReportHeader,
new Font(new Font(gw.Font, FontStyle.Bold),
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
//Draw Columns
iTopMargin = e.MarginBounds.Top+30;
DataGridViewColumn[] _GridCol = new DataGridViewColumn[gw.Columns.Count];
int colcount = 0;
//Convert ltr to rtl
foreach (DataGridViewColumn GridCol in gw.Columns)
{
_GridCol[colcount++] = GridCol;
}
for (int i =0; i <= (_GridCol.Count() - 1); i++)
{
e.Graphics.FillRectangle(new SolidBrush(Color.Gainsboro),
new Rectangle((int) arrColumnLefts[iCount], iTopMargin,
(int) arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawRectangle(new Pen(Color.Black),
new Rectangle((int) arrColumnLefts[iCount], iTopMargin,
(int) arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawString(_GridCol[i].HeaderText,
new Font("Calibri Light", 12, FontStyle.Bold),
new SolidBrush(Color.Black),
new RectangleF((int) arrColumnLefts[iCount], iTopMargin,
(int) arrColumnWidths[iCount], iHeaderHeight), strFormat);
iCount++;
}
bNewPage = false;
iTopMargin += iHeaderHeight;
}
iCount = 0;
DataGridViewCell[] _GridCell = new DataGridViewCell[GridRow.Cells.Count];
int cellcount = 0;
//Convert ltr to rtl
foreach (DataGridViewCell Cel in GridRow.Cells)
{
_GridCell[cellcount++] = Cel;
}
//Draw Columns Contents
for (int i =0; i <=(_GridCell.Count() - 1); i++)
{
if (_GridCell[i].Value != null)
{
if (_GridCell[i].GetType() != typeof (DataGridViewImageCell))
{
e.Graphics.DrawString(_GridCell[i].FormattedValue.ToString(),
new Font("Calibri Light", 10),
new SolidBrush(Color.Black),
new RectangleF((int) arrColumnLefts[iCount],
(float) iTopMargin,
(int) arrColumnWidths[iCount], (float) iCellHeight),
strFormat);
}
else
{
Image img = Common.byteArrayToImage((byte[]) _GridCell[i].Value);
Rectangle m = new Rectangle((int) arrColumnLefts[iCount],iTopMargin,
(int) arrColumnWidths[iCount], iCellHeight);
if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
}
e.Graphics.DrawImage(img, m);
}
}
//Drawing Cells Borders
e.Graphics.DrawRectangle(new Pen(Color.Black),
new Rectangle((int) arrColumnLefts[iCount], iTopMargin,
(int) arrColumnWidths[iCount], iCellHeight));
iCount++;
}
}
iRow++;
iTopMargin += iCellHeight;
}
//If more lines exist, print another page.
if (bMorePagesToPrint)
e.HasMorePages = true;
else
e.HasMorePages = false;
//}
//catch (Exception exc)
//{
// KryptonMessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
// MessageBoxIcon.Error);
//}
}
private void _printDocument_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
try
{
strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Center;
strFormat.LineAlignment = StringAlignment.Center;
strFormat.Trimming = StringTrimming.EllipsisCharacter;
arrColumnLefts.Clear();
arrColumnWidths.Clear();
iCellHeight = 0;
iRow = 0;
bFirstPage = true;
bNewPage = true;
// Calculating Total Widths
iTotalWidth = 0;
foreach (DataGridViewColumn dgvGridCol in gw.Columns)
{
iTotalWidth += dgvGridCol.Width;
}
}
catch (Exception ex)
{
KryptonMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
as
ClsPrint _ClsPrint = new ClsPrint(myDataGridView, "MyHeader");
_ClsPrint.PrintForm();

Your position variables are being declared inside the loop, meaning that they are reset for each pass through the loop. Keep position variables for X and Y outside of the loop over serial and adjust it for the total width (and height, if you start a new row of barcodes) of each barcode.

Related

Create multiple label over the multiple ellipse

I have 6 ellipse and 6 label. I want to add labels over the ellipse. 2 of labels is OK but the others not.
In debug mode there is no error.
Here is the code:
private void Form1_Paint(object sender, PaintEventArgs e)
{
int locY = 200, locX = 10, i = 0;
for (int k = 0; k < 3; k++)
{
locX += 40;
for (int j = 0; j < 2; j++)
{
locY += 30;
Pen pen = new Pen(Color.Red, 10);
e.Graphics.DrawEllipse(pen, new Rectangle(locX, locY, 10, 10));
Label label = new Label();
label.Text = i.ToString();
label.Location = new Point(locX,locY);
label.BackColor = Color.Transparent;
Controls.Add(label);
i++;
}
locY = 200;
}
}
Here is the output:
You should also create that Pen outside of the loop and make sure to dispose of it.
Here's an example using DrawString() as described in the comments:
private void Form1_Paint(object sender, PaintEventArgs e)
{
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
int locY = 200, locX = 10, i = 0;
using (Pen pen = new Pen(Color.Red, 10))
{
for (int k = 0; k < 3; k++)
{
locX += 40;
for (int j = 0; j < 2; j++)
{
locY += 30;
Rectangle rc = new Rectangle(locX, locY, 10, 10);
e.Graphics.DrawEllipse(pen, rc);
SizeF szF = e.Graphics.MeasureString(i.ToString(), this.Font);
Rectangle rc2 = new Rectangle(new Point(rc.Left + rc.Width / 2, rc.Top + rc.Height / 2), new Size(1, 1));
rc2.Inflate((int)szF.Width, (int)szF.Height);
e.Graphics.DrawString(i.ToString(), this.Font, Brushes.Black, rc2, sf);
i++;
}
locY = 200;
}
}
}

Change color of only part of text inside a data grid view cell by using c#

I want to change color the given search text in the DataGridView but the data is in Arabic. I have tried CellPainting event to find the bounds of the search text and draw FillRectangle, but I want to change color not highlight for search text.
Here are two figures:
The first figure I want is the same:
The second figure of the form I used:
This is the code that I used
if ((e.RowIndex <= -1 ? false : e.ColumnIndex > -1))
{
string str = txtSearch.Text.Trim();
if (!string.IsNullOrWhiteSpace(str))
{
string[] strArrays = str.Split(new char[] { ' ' });
List<Rectangle> rectangles = new List<Rectangle>();
string[] strArrays1 = strArrays;
for (int i = 0; i < (int)strArrays1.Length; i++)
{
string str1 = strArrays1[i];
string str2 = e.FormattedValue.ToString();
int num = str2.ToLower().IndexOf(str1.ToLower());
if (num >= 0)
{
e.Handled = true;
e.PaintBackground(e.CellBounds, true);
Rectangle y = new Rectangle();
Rectangle cellBounds = e.CellBounds;
y.Y = cellBounds.Y + 2;
cellBounds = e.CellBounds;
y.Height = cellBounds.Height - 5;
string str3 = str2.Substring(0, num);
string str4 = str2.Substring(num, str1.Length);
Graphics graphics = e.Graphics;
Font font = e.CellStyle.Font;
cellBounds = e.CellBounds;
Size size = TextRenderer.MeasureText(graphics, str2, font, cellBounds.Size);
Graphics graphic = e.Graphics;
Font font1 = e.CellStyle.Font;
cellBounds = e.CellBounds;
Size size1 = TextRenderer.MeasureText(graphic, str3, font1, cellBounds.Size);
Graphics graphics1 = e.Graphics;
Font font2 = e.CellStyle.Font;
cellBounds = e.CellBounds;
Size size2 = TextRenderer.MeasureText(graphics1, str4, font2, cellBounds.Size);
cellBounds = e.CellBounds;
int width = (cellBounds.Width - size.Width) / 2;
int x = e.CellBounds.X;
cellBounds = e.CellBounds;
int width1 = x + cellBounds.Width;
y.X = width1 - size1.Width - size2.Width + 5 - width;
y.Width = size2.Width;
rectangles.Add(y);
}
}
if (rectangles.Count > 0)
{
SolidBrush solidBrush = new SolidBrush(Color.Yellow);
foreach (Rectangle rectangle in rectangles)
{
e.Graphics.FillRectangle(solidBrush, rectangle);
}
solidBrush.Dispose();
e.PaintContent(e.CellBounds);
}
}
}
Graphics.FillRectangle will not change the ForeColor.I have modified then CellPainting event.I am using the Graphics.DrawString for changing the ForeColor.
if ((e.RowIndex <= -1 ? false : e.ColumnIndex > -1))
{
string str = txtSearch.Text.Trim();
if (!string.IsNullOrWhiteSpace(str))
{
string[] strArrays = str.Split(new char[] { ' ' });
string[] strArrays1 = strArrays;
for (int i = 0; i < (int)strArrays1.Length; i++)
{
string str1 = strArrays1[i];
string str2 = e.FormattedValue.ToString();
int num = str2.ToLower().IndexOf(str1.ToLower());
if (num >= 0)
{
e.Handled = true;
e.PaintBackground(e.CellBounds, true);
Size size = TextRenderer.MeasureText(e.Graphics, str2, e.CellStyle.Font, e.CellBounds.Size);
Size searchSize = TextRenderer.MeasureText(e.Graphics, str1, e.CellStyle.Font, e.CellBounds.Size);
List<int> indexes = str2.AllIndexesOf(str1).ToList<int>();
string leadingPart = string.Empty;
string printString = string.Empty;
for (int index = 0; index < str2.Length; index++)
{
if (indexes.Contains(index))//Search string starts here
{
leadingPart = str2.Substring(0, index);//leading part of the string
Size leadingSize = TextRenderer.MeasureText(e.Graphics, leadingPart, e.CellStyle.Font, e.CellBounds.Size);
Rectangle rect = new Rectangle(new Point(e.CellBounds.X + leadingSize.Width, e.CellBounds.Y + 4), searchSize);
SolidBrush brush = new SolidBrush(Color.Green);
e.Graphics.DrawString(str1, e.CellStyle.Font, brush, rect);
brush.Dispose();
index += str1.Length - 1;
}
else
{
int nextIndex = indexes.FirstOrDefault(x => x > index);
leadingPart = str2.Substring(0, index);
printString = index < nextIndex ? str2.Substring(index, nextIndex - index) : str2.Substring(index);
Size leadingSize = TextRenderer.MeasureText(e.Graphics, leadingPart, e.CellStyle.Font, e.CellBounds.Size);
Size printSize = TextRenderer.MeasureText(e.Graphics, printString, e.CellStyle.Font, e.CellBounds.Size);
Rectangle rect;
if (index > 0)
rect = new Rectangle(new Point(e.CellBounds.X + leadingSize.Width, e.CellBounds.Y + 4), printSize);//4 is for adjusting the text top position
else
rect = new Rectangle(new Point(e.CellBounds.X, e.CellBounds.Y + 4), printSize);
SolidBrush brush = new SolidBrush(Color.Black);
e.Graphics.DrawString(printString, e.CellStyle.Font, brush, rect);
brush.Dispose();
index += printString.Length - 1;
}
}
}
}
}
}
Note that AllIndexesOf is an extension method for finding all the occurrences of a particular string in a given long string, which I got from this post.
public static IEnumerable<int> AllIndexesOf(this string sourceString, string subString)
{
return Regex.Matches(sourceString, subString,RegexOptions.IgnoreCase).Cast<Match>().Select(m => m.Index);
}
Hope this helps.

Place a grid of labels on a form

I'm trying to place a grid of labels on my winforms app. First, I'm populating a list of label objects of size (200 x 50) and then trying to place them so that when x reaches the width of the form (581), I increment y by 50 + 1
Here is my code:
private List<Label> _labels;
private int xOffset = 10;
private int yOffset = 10;
public Form1()
{
InitializeComponent();
_labels = new List<Label>();
for(var i = 0; i <= 20; i++)
_labels.Add(new Label() { Name = "lbl" + i, Height = 50, Width = 200, MinimumSize = new Size(200, 50), BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D, Text = "Label "+i});
// 581, 517
var x = 0;
var y = 0;
foreach (var lbl in _labels)
{
if (x >= 580)
{
x = 0;
y = y + lbl.Height + 2;
lbl.Location = new Point(x, y);
}
this.Controls.Add(lbl);
x += x + lbl.Width;
}
}
It's only placing the even labels from the list on new lines. I'm not sure what I'm doing wrong.
I'm trying to place all of the labels in a grid like design. When one row is full, go to the next row and continue placing labels from the list on that new "row"
You need to move the Location setting code out of the resetting loop:
foreach (var lbl in _labels)
{
if (x >= 580)
{
x = 0;
y = y + lbl.Height + 2;
}
lbl.Location = new Point(x, y);
this.Controls.Add(lbl);
x += lbl.Width;
}
The problematic part is here
x += x + lbl.Width; //+= x
change it to
x += lbl.Width;
Get the
lbl.Location = new Point(x, y);
out of the if statement
if (x >= 580)
{
x = 0;
y = y + lbl.Height + 2;
//lbl.Location = new Point(x, y);
}
lbl.Location = new Point(x, y);
this.Controls.Add(lbl);
x += lbl.Width;
Try this using a Docked FlowLayoutPanel:
public partial class Form1 : Form
{
List<Label> labels;
public Form1()
{
InitializeComponent();
this.labels=new List<Label>();
AddLabelsToFrom(20);
}
void AddLabelsToFrom(int count)
{
for (int i=0; i<count; i++)
{
var lbl=new Label() { Name="lbl"+i, Height=50, Width=200, MinimumSize=new Size(200, 50), BorderStyle=System.Windows.Forms.BorderStyle.Fixed3D, Text="Label "+i };
labels.Add(lbl);
flowLayoutPanel1.Controls.Add(lbl);
}
}
}
void SetGridLabel()
{
for (int i = 0; ; i++)
{
for (int j = 0; ; j++)
{
Label L = new Label();
L.TextAlign = ContentAlignment.MiddleCenter;
L.AutoSize = false;
L.Size = new Size(70, 70);
L.Text = "Test_" + j + "_" + i;
L.Location = new Point(j * L.Size.Width, i * L.Size.Height);
if ((i + 1) * L.Size.Height > this.Size.Height)
return;
if ((j + 1) * L.Size.Width > this.Size.Width)
break;
this.Controls.Add(L);
}
}
}
private List<Label> _labels;
public Form1()
{
InitializeComponent();
_labels = new List<Label>();
for (var i = 0; i <= 20; i++)
_labels.Add(new Label()
{
Name = "lbl" + i, Height = 50,Width = 200,
Size = MinimumSize = new Size(200, 50),
Location = new Point(i * 200 % 600, 50 * (i * 200 / 600)),
BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D,
Text = "Label " + i
});
foreach (var lbl in _labels) this.Controls.Add(lbl);
}

How to assign table cell width on runtime dynamically in C#?

I have a function in devexpress report which creates table from SQL query dynamically:
readonly int[] cellWidth = { 5, 20, 30, 40, 50, 60 };// { 16, 100, 100, 30, 20, 16 };
private XRTable CreateXRTableDetail(DataTable dtAra)
{
XRTable table = new XRTable();
table.BeginInit();
table.LocationFloat = new DevExpress.Utils.PointFloat(0, 5F);
table.Borders = BorderSide.All;
int tableHeight = 0;
int tableWidth = 0;
for (int i = -1; i < 4; i++)
{
XRTableRow row = new XRTableRow();
for (int j = 0; j < 6; j++)
{
XRTableCell cell = new XRTableCell();
cell.Padding = 1;
Unit width = new Unit(cellWidth[j], UnitType.Pixel);
cell.Width = (int)width.Value;
cell.Weight = 1;
cell.TextAlignment = TextAlignment.MiddleCenter;
tableWidth += cell.Width;
if (i == -1)//Header
{
row.Height = 15;
cell.Text = dtAra.Columns[j].ColumnName;
cell.BackColor = Color.Gainsboro;
cell.Font = new Font("tahoma", 6);
}
else
{
row.Height = 40;
cell.Text = dtAra.Rows[i][j].ToString();
cell.Font = new Font("tahoma", 5);
}
row.Cells.Add(cell);
}
tableHeight += row.Height;
table.Rows.Add(row);
}
tableWidth = tableWidth / table.Rows.Count;
table.Size = new Size(tableWidth, tableHeight);
table.EndInit();
return table;
}
I assing cell widths from cellWidth array but all columns are initialising with same width.
How can I set cell width as I want?
Try this:
int width = 40;
cell.SizeF = new SizeF(cell.SizeF.Width + width, cell.SizeF.Height);

Getting exception "Parameter is not valid" when minimizing the form to the taskbar

It happen only when I resize the form when the program is running.
I click the "-" and the program is minimised to the taskbar, then I see the error/exception message.
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);
if (!_addingLines)
SplitText(this.Text);
if (_backBmpBU != null)
this._backBmp = MakeBackBmp(_backBmpBU);
if (this.BitmapModus)
{
UpdateBitmap();
}
}
private void UpdateBitmap()
{
if (_lines != null && _lines.Length > 0)
{
SizeF sz = new SizeF(0, 0);
float lineOrigHeight = sz.Height;
using (Graphics g = this.CreateGraphics())
{
sz = g.MeasureString("Teststring", this.Font);
if (this._additionalSpaceBetweenLines > 0)
sz = new SizeF(sz.Width, sz.Height + this._additionalSpaceBetweenLines);
}
this._textHeight = sz.Height * _lines.Length;
if (_bmp != null)
{
_bmp.Dispose();
_bmp = null;
}
try
{
if (this._textHeight > MAXHEIGHT)
throw new Exception("Text too long, for BitmapMode.");
_bmp = new Bitmap(this.ClientSize.Width, (int)Math.Ceiling(this._textHeight));
using (Graphics g = Graphics.FromImage(_bmp))
{
//set it to value you like...
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
using (SolidBrush b = new SolidBrush(this.ForeColor))
{
for (int i = 0; i < _lines.Length; i++)
{
SolidBrush bb = b;
if (TrimText)
_lines[i] = _lines[i].Trim();
sz = g.MeasureString(_lines[i], this.Font);
lineOrigHeight = sz.Height;
if (this._additionalSpaceBetweenLines > 0)
sz = new SizeF(sz.Width, sz.Height + this._additionalSpaceBetweenLines);
_posX = 0;
if (this.TextLayoutCentered)
_posX = (this.ClientSize.Width - sz.Width) / 2.0F;
bool drect = false;
bool colw = false;
int indx = -1;
int length = 0;
string textToFind = "";
Color fc = this.ForeColor;
Color bc = Color.Transparent;
Color rc = Color.Transparent;
if (Words != null && Words.Count > 0)
{
for (int ii = 0; ii < Words.Count; ii++)
{
if (_lines[i].Contains(Words[ii].WordOrText))
{
bb = new SolidBrush(Words[ii].ForeColor);
if (Words[ii].DrawRect)
drect = true;
if (Words[ii].ColorOnlyThisWord)
colw = true;
indx = _lines[i].IndexOf(Words[ii].WordOrText);
length = Words[ii].WordOrText.Length;
textToFind = Words[ii].WordOrText;
fc = Words[ii].ForeColor;
bc = Words[ii].BackColor;
rc = Words[ii].RectColor;
drect = Words[ii].DrawRect;
}
}
}
if (colw)
{
//reset b and create a new color brush
if (bb.Equals(b) == false)
bb.Dispose();
bb = b;
string ftext = _lines[i];
float cPosX = _posX;
using (SolidBrush bbb = new SolidBrush(fc))
{
while (indx > -1)
{
if (indx > 0)
g.DrawString(ftext.Substring(0, indx), this.Font, bb, new PointF(cPosX, sz.Height * i + _additionalSpaceBetweenLines / 2F));
cPosX += g.MeasureString(ftext.Substring(0, indx), this.Font).Width;
SizeF sfWord = g.MeasureString(ftext.Substring(indx, length), this.Font);
if (bc.ToArgb().Equals(Color.Transparent.ToArgb()) == false)
{
using (SolidBrush bbbb = new SolidBrush(bc))
g.FillRectangle(bbbb, cPosX, sz.Height * i + _additionalSpaceBetweenLines / 2F, sfWord.Width, sfWord.Height);
}
g.DrawString(ftext.Substring(indx, length), this.Font, bbb, new PointF(cPosX, sz.Height * i + _additionalSpaceBetweenLines / 2F));
cPosX += sfWord.Width;
ftext = ftext.Substring(indx + length);
if (textToFind.Length > 0)
indx = ftext.IndexOf(textToFind);
else
indx = -1;
}
if (ftext.Length > 0)
g.DrawString(ftext, this.Font, bb, new PointF(cPosX, sz.Height * i + _additionalSpaceBetweenLines / 2F));
}
}
else
{
if (bc.ToArgb().Equals(Color.Transparent.ToArgb()) == false)
{
using (SolidBrush bbbb = new SolidBrush(bc))
g.FillRectangle(bbbb, _posX, sz.Height * i + _additionalSpaceBetweenLines / 2F, sz.Width, lineOrigHeight);
}
g.DrawString(_lines[i], this.Font, bb, new PointF(_posX, sz.Height * i + _additionalSpaceBetweenLines / 2F));
}
if (drect)
{
if (rc.ToArgb().Equals(Color.Transparent.ToArgb()) == false)
using (Pen p = new Pen(rc))
g.DrawRectangle(p, _posX, sz.Height * i + _additionalSpaceBetweenLines / 2F, sz.Width, lineOrigHeight);
}
if (bb.Equals(b) == false)
bb.Dispose();
if (DrawRect)
{
using (Pen p = new Pen(this.ForeColor))
{
if (DrawRectAroundText)
g.DrawRectangle(p, _posX, sz.Height * i + _additionalSpaceBetweenLines / 2F, sz.Width, lineOrigHeight);
else
g.DrawRectangle(p, 0, sz.Height * i + _additionalSpaceBetweenLines / 2F, this.ClientSize.Width - 1, lineOrigHeight);
}
}
}
}
}
}
catch (Exception ex)
{
if (_bmp != null)
{
_bmp.Dispose();
_bmp = null;
}
this.BitmapModus = false;
//MessageBox.Show(ex.Message + " switching to Dynamic-Draw-Mode.");
OnSwitchModeOnError();
}
}
}
When the program is running and i minimize the form to the taskbar im getting exception:
Parameter is not valid
The full exception message:
System.ArgumentException was caught
HResult=-2147024809
Message=Parameter is not valid.
Source=System.Drawing
StackTrace:
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)
at ScrollLabelTest.ScrollLabel.UpdateBitmap() in e:\scrolllabel\ScrollLabel\ScrollLabel\ScrollLabel.cs:line 601
InnerException:
I had the same problem, with a huge list of errors in the Just-In-Time-Debugger. After several hours of searching I found my own way. Try this, no more exceptions!!
private void picMinimize_Click(object sender, EventArgs e)
{
try
{
panelUC.Visible = false; //change visible status of your form, etc.
this.WindowState = FormWindowState.Minimized; //minimize
minimizedFlag = true; //set a global flag
}
catch (Exception)
{
}
}
private void mainForm_Resize(object sender, EventArgs e)
{
//check if form is minimized, and you know that this method is only called if and only if the form get a change in size, meaning somebody clicked in the taskbar on your application
if (minimizedFlag == true)
{
panelUC.Visible = true; //make your panel visible again! thats it
minimizedFlag = false; //set flag back
}
}
Thumb up!

Categories