Text Alignment on OwnerDraw Tooltip in C# / .NET - c#

I have a multiline text string (e.g. "Stuff\nMore Stuff\nYet More Stuff"), and I want to paint it, along with a bitmap into a tooltip. Since I am painting the bitmap, I need to set OwnerDraw to true, which I am doing. I am also handling the Popup event, so I can size the tooltip to be large enough to hold the text and the bitmap.
I am calling e.DrawBackground and e.DrawBorder(), and then painting my bitmap on the left side of the tooltip area.
Is there a set of flags I can pass to e.DrawText() in order to left-align the text, but to offset it so that it doesn't get painted over my bitmap? Or do I need to custom draw all the text as well (which will probably involve splitting the string on newlines, etc)?
UPDATED: The final code looks like this:
private void _ItemTip_Draw(object sender, DrawToolTipEventArgs e)
{
e.DrawBackground();
e.DrawBorder();
// Reserve a square of size e.Bounds.Height x e.Bounds.Height
// for the image. Keep a margin around it so that it looks good.
int margin = 2;
Image i = _ItemTip.Tag as Image;
if (i != null)
{
int side = e.Bounds.Height - 2 * margin;
e.Graphics.DrawImage(i, new Rectangle(margin, margin, side, side));
}
// Construct bounding rectangle for text (don't want to paint it over the image).
int textOffset = e.Bounds.Height + 2 * margin;
RectangleF rText = e.Bounds;
rText.Offset(textOffset, 0);
rText.Width -= textOffset;
e.Graphics.DrawString(e.ToolTipText, e.Font, Brushes.Black, rText);
}

I assume that if you define the bounding rectangle to draw in (calculating the image offset yourself) you could just:
RectangleF rect = new RectangleF(100,100,100,100);
e.Graphics.DrawString(myString, myFont, myBrush, rect);

to calculate the Height of an owner drawn string s given a certain width w, we use the following code:
double MeasureStringHeight (Graphics g, string s, Font f, int w) {
double result = 0;
int n = s.Length;
int i = 0;
while (i < n) {
StringBuilder line = new StringBuilder();
int iLineStart = i;
int iSpace = -1;
SizeF sLine = new SizeF(0, 0);
while ((i < n) && (sLine.Width <= w)) {
char ch = s[i];
if ((ch == ' ') || (ch == '-')) {
iSpace = i;
}
line.Append(ch);
sLine = g.MeasureString(line.ToString(), f);
i++;
}
if (sLine.Width > w) {
if (iSpace >= 0) {
i = iSpace + 1;
} else {
i--;
}
// Assert(w > largest ch in line)
}
result += sLine.Height;
}
return result;
}
Regards,
tamberg

Related

Show tooltip for part of user control

I'm building custom control that will display tiles, like colored grid.
I've managed to do drawing, scrolling and basic logic, but I have problem with creating tooltip for each tile.
Each tile color depends on data that is "bound" to that tile.
I'll try to describe my idea:
Above image shows my control, I have 4 squares drawn there, I'd like to show different tooltip when user hovers different parts of my control.
Below is my tooltip (small red rectangle) and lower is standard WinForms Chart component.
I'd like to get this kind of behavior in my control (tooltip is outside of control, so long text is displayed properly).
Below is code of my control with just basic functionality:
public sealed class UC1 : UserControl
{
private bool _showTooltip;
private string _tooltipText;
private Point _mousePosition;
public UC1()
{
MinimumSize = new Size(100, 100);
Size = new Size(100, 100);
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.FillRectangle(Brushes.LightGoldenrodYellow, 0, 0, Width/2, Height/2);
e.Graphics.FillRectangle(Brushes.LightGray, Width/2, 0, Width, Height/2);
e.Graphics.FillRectangle(Brushes.LightSlateGray, 0, Height/2, Width/2, Height);
e.Graphics.FillRectangle(Brushes.LightSteelBlue, Width/2, Height/2, Width, Height);
using (var p = new Pen(Color.Black, 2))
{
e.Graphics.DrawLine(p, Width/2, 0, Width/2, Height);
e.Graphics.DrawLine(p, 0, Height/2, Width, Height/2);
}
if (_showTooltip)
{
SizeF c = e.Graphics.MeasureString(_tooltipText, DefaultFont);
int width = (int) c.Width;
int height = (int) c.Height;
const int offset = 12;
var x = _mousePosition.X + width + offset > Width ? _mousePosition.X - width : _mousePosition.X + offset;
var y = _mousePosition.Y + height + offset > Height ? _mousePosition.Y - height : _mousePosition.Y + offset;
e.Graphics.FillRectangle(Brushes.Red, x, y, width, height);
e.Graphics.DrawString(_tooltipText, DefaultFont, Brushes.Black, x, y);
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.X > 0 && e.X < Width/2 && e.Y > 0 && e.Y < Height/2)
{
Debug.WriteLine("1,1 square");
_tooltipText = "1,1";
}
else if (e.X > Width/2 && e.X < Width && e.Y > 0 && e.Y < Height/2)
{
Debug.WriteLine("1,2 square");
_tooltipText = "1,2";
}
else if (e.X > 0 && e.X < Width/2 && e.Y > Height/2 && e.Y < Height)
{
Debug.WriteLine("2,1 square");
_tooltipText = "2,1";
}
else if (e.X > Width/2 && e.X < Width && e.Y > Height/2 && e.Y < Height)
{
Debug.WriteLine("2,2 square");
_tooltipText = "2,2";
}
_mousePosition = e.Location;
_showTooltip = true;
Refresh();
}
protected override void OnMouseLeave(EventArgs e)
{
_showTooltip = false;
Refresh();
base.OnMouseLeave(e);
}
}
I've found similar question: How to make a floating (tooltip) control in Windows.Forms? but I'd like to avoid creating custom tooltip and instead use standard one.
How can I show standard tooltip that will change it text when hovering on different tiles. I'd like to add everything to my user control, so I won't have to add any code to form hosting my control.
Why do you try to draw the ToolTip yourself instead of using the system one?
Just add one to the UC class
// private bool _showTooltip; ?? probably not needed any more..
private string _tooltipText;
// private Point _mousePosition; ??..
ToolTip ttip = new ToolTip();
and set it like this:
// _mousePosition = e.Location; ??..
// _showTooltip = true; ??..
ttip.SetToolTip(this, _tooltipText); // use this in the mousemove
Refresh();
Of course now you can skip the whole Painting part..
If you want to control the location where the ToolTip is shown use one of the ShowToolTip() overloads instead of SetToolTip() ..!
While both are still there this is the result, going over the UC's border and displaying with a nice drop shadow..:
If you really want your ToolTip to look different from the usual ones, you can set its OwnerDraw to true and code its Draw event just like any other control with GDI+ graphics methods..
Update:
There is an inherent flicker problem; for an explanation see Hans' answer here; his recommendation #2 and one of the answers is helpful:
Remember last mouse position and set the tooltip only when the mouse
position changes.
So we need to add a last ToolTip location:
Point tipLoc = Point.Empty;
Which we test and set in the mouse move:
if (tipLoc != e.Location )
{
tipLoc = e.Location;
ttip.SetToolTip(this, _tooltipText);
}

How can i load information from a txt file to show on a panel?

So i am using this method to save data into a txt file :
private void button1_Click(object sender, EventArgs e)
{
using (StreamWriter objWriter = new StreamWriter("test1.txt"))
{
objWriter.Write(textBox1.Text);
objWriter.Write(textBox2.Text);
objWriter.Write(comboBox1.Text);
objWriter.Write(comboBox2.Text);
MessageBox.Show("Details have been saved");
}
}
all those textbox and combobox are in a form called NewAppointment. And this is the panel in my MainForm:
private void panelDailyView_Paint(object sender, PaintEventArgs e)
{
int paintWidth = panelDailyView.ClientRectangle.Size.Width - vScrollBar.Width;
int paintHeight = panelDailyView.ClientRectangle.Size.Height;
int displayedRowCount = paintHeight / PanelRowHeight;
int panelTopRow;
int nextRow;
int apptStartRow;
int apptLength;
string dispTime;
Font font = new Font("Arial", 10);
Brush drawBrush = new SolidBrush(Color.DarkBlue);
Brush appointmentBrush = new SolidBrush(Color.LightBlue);
Graphics g = e.Graphics;
// Fill the background of the panel
g.FillRectangle(new SolidBrush(Color.Linen), 0, 0, paintWidth, paintHeight);
panelTopRow = vScrollBar.Value;
if (_SelectedRow >= panelTopRow &&
_SelectedRow <= panelTopRow + displayedRowCount)
{
// If the selected time is displayed, mark it
g.FillRectangle(new SolidBrush(Color.DarkKhaki),
0,
(_SelectedRow - panelTopRow) * PanelRowHeight,
paintWidth,
PanelRowHeight);
}
// Display the times at the start of the rows and
// the lines separating the rows
nextRow = panelTopRow;
for (int i = 0; i <= displayedRowCount; i++)
{
dispTime = (nextRow / 2).ToString("0#") + (nextRow % 2 == 0 ? ":00" : ":30");
nextRow++;
g.DrawString(dispTime, font, drawBrush, 2, (i * PanelRowHeight + 4));
g.DrawLine(Pens.DarkBlue, 0, i * PanelRowHeight, paintWidth, i * PanelRowHeight);
}
// Now fill in the appointments
foreach (IAppointment appointment in _TodaysAppointments)
{
apptStartRow = Utility.ConvertTimeToRow(appointment.Start);
apptLength = Utility.ConvertLengthToRows(appointment.Length);
// See if the appointment is inside the part of the day displayed on the panel
if (((apptStartRow >= panelTopRow) &&
(apptStartRow <= panelTopRow + displayedRowCount)) ||
(apptStartRow + apptLength > panelTopRow))
{
// Calculate the area of the panel occupied by
// the appointment
if (apptStartRow < panelTopRow)
{
apptLength = apptLength - (panelTopRow - apptStartRow);
apptStartRow = panelTopRow;
}
int apptDispStart = (apptStartRow - panelTopRow) * PanelRowHeight;
int apptDispLength = apptLength * PanelRowHeight;
if (apptDispStart + apptDispLength > paintHeight)
{
apptDispLength = paintHeight - apptDispStart;
}
Rectangle apptRectangle = new Rectangle(ApptOffset,
apptDispStart,
paintWidth - (ApptOffset * 2),
apptDispLength);
// Draw the block of light blue
g.FillRectangle(appointmentBrush,
apptRectangle);
// Draw the black line around it
g.DrawRectangle(Pens.Black, apptRectangle);
if (Utility.ConvertTimeToRow(appointment.Start) >= panelTopRow)
{
// If the top line of the appointment is displayed,
// write out the subject and location. Temporarily
// reduce the clip area for the graphics object to ensure
// that the text does not extend beyond the rectangle
Region oldClip = g.Clip;
g.Clip = new Region(apptRectangle);
g.DrawString(appointment.DisplayableDescription,
font,
drawBrush,
ApptOffset + 6,
apptDispStart + 4);
g.Clip = oldClip;
}
}
}
}
All i want to do is to load all the information saved in that .txt file to the panel.
// replace filepath below with filepath of your text file.
string text = System.IO.File.ReadAllText(#"C:\Users\Public\TestFolder\WriteText.txt");
Once you have the text variable populated, you can do whatever you want with it. Like add it to your panel.
// something like...
panel.Text = text;
You can also read each line of the text file into an array and do whatever you like with the array:
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\Public\TestFolder\WriteLines.txt");

Drawing on Image

I'm able to draw on the image using the below code. But my problem is, it is not a continuous line. It looks somehow broken. See below image for better understanding.
My XAML :
<Grid x:Name="Gridimage1" Grid.Column="0">
<Image Name="image1" HorizontalAlignment="Left" VerticalAlignment="Top" Stretch="Fill" >
</Image>
</Grid>
My c# code :
#region "Drawing on image"
static WriteableBitmap writeableBitmap;
static Image i;
public void DrawingOnImage() // this function will be called after image load
{
if (image1.Source != null)
{
i = new Image();
RenderOptions.SetBitmapScalingMode(image1, BitmapScalingMode.NearestNeighbor);
RenderOptions.SetEdgeMode(image1, EdgeMode.Aliased);
BitmapSource BitmapSrc = new FormatConvertedBitmap(image1.Source as BitmapSource, PixelFormats.Default, null, 0);
//writeableBitmap = new WriteableBitmap((int)image1.ActualWidth, (int)image1.ActualHeight, 96, 96, PixelFormats.Bgr32, null);
writeableBitmap = new WriteableBitmap(BitmapSrc);
image1.Source = writeableBitmap;
//image1.Stretch = Stretch.None;
image1.HorizontalAlignment = HorizontalAlignment.Left;
image1.VerticalAlignment = VerticalAlignment.Top;
i = image1;
image1.MouseMove += new MouseEventHandler(i_MouseMove);
image1.MouseLeftButtonDown +=
new MouseButtonEventHandler(i_MouseLeftButtonDown);
image1.MouseRightButtonDown +=
new MouseButtonEventHandler(i_MouseRightButtonDown);
}
}
static void i_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DrawPixel(e);
}
static void i_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
DrawPixel(e);
}
}
static void DrawPixel(MouseEventArgs e)
{
double CR = i.Source.Height / i.ActualHeight;
double RR = i.Source.Width / i.ActualWidth;
int column = (int)(e.GetPosition(i).X * RR) ;
int row = (int)(e.GetPosition(i).Y * CR);
// Reserve the back buffer for updates.
writeableBitmap.Lock();
unsafe
{
// Get a pointer to the back buffer.
int pBackBuffer = (int)writeableBitmap.BackBuffer;
// Fin d the address of the pixel to draw.
pBackBuffer += row * writeableBitmap.BackBufferStride;
pBackBuffer += column * 4;
// Compute the pixel's color.
int color_data = 255 << 16; // R
color_data |= 128 << 8; // G
color_data |= 255 << 0; // B
// Assign the color data to the pixel.
*((int*)pBackBuffer) = color_data;
}
// Specify the area of the bitmap that changed.
writeableBitmap.AddDirtyRect(new Int32Rect(column, row, 1, 1));
// Release the back buffer and make it available for display.
writeableBitmap.Unlock();
}
#endregion
Image output :
You can see the line (pink color) I have drawn. It's not a continuous line. Where am I failing?
Update :
My findings after #loxxy's Inputs.Set oldx ,oldy to zero initialy.
if (oldx == 0 && oldy == 0)
{
writeableBitmap.DrawLineAa(column, row, column, row, SelectedColor);
}
else
{
if (Math.Abs(oldx - column) > 10 || Math.Abs(oldy - row) > 10)
{
writeableBitmap.DrawLineAa(column, row, column, row, SelectedColor);
}
else
{
writeableBitmap.DrawLineAa(column, row, oldx, oldy, SelectedColor);
}
}
oldx = column;
oldy = row;
Since you are drawing it pixel by pixel, the mouse has to update the coordinates at a much faster rate.
And I believe it relates to the DPI of the mouse... And you can do nothing about that.
So instead try drawing a line. So something like this in WPF:
WriteableBitmapExtensions.DrawLine
The mouse events you receive will not return consecutive points. If you move the mouse fast, the points returned will not be next to each other. If you want to draw a line under the mouse cursor, you need to draw a line from the previous point drawn to the current point on every MouseMove or MouseButtonDown callback.

C#: TreeView owner drawing with ownerdrawtext and the weird black highlighting when clicking on a node

I set the DrawMode to OwnerDrawText and tacked on to the DrawNode event, added my code to draw the text the way I want and all works well save for some odd black selection highlighting when a node is selected.
No problem, I added logic to check for if the node's state was highlighted and drew my own highlighting except the black highlighting gets added when a node is clicked, not just selected... The highlight gets drawn over by my rectangle once the mouse button is released but does get drawn and blinks...it's annoying. :/
Apparently I forgot to actually ask my question...How would one go about getting rid of the selection without completely handling the drawing?
In my experience you usually can't. Either you draw the item yourself or you don't. If you try to composite your graphics on top of those drawn by the control, you'll end up with glitches.
It is a bit of a pain because you have to handle focus rectangles, selection highlights, and drawing all the glyphs yourself.
On the plus side, Visual Styles can be used to do most of the work.
Here's some code that will get you most of the way there (it's incomplete, in that it uses some methods not included, and it doesn't render exactly what a normal treeview does because it supports grad filled items and columns, but should be a handy reference)
protected virtual void OnDrawTreeNode(object sender, DrawTreeNodeEventArgs e)
{
string text = e.Node.Text;
Rectangle itemRect = e.Bounds;
if (e.Bounds.Height < 1 || e.Bounds.Width < 1)
return;
int cIndentBy = 19; // TODO - support Indent value
int cMargin = 6; // TODO - this is a bit random, it's slaved off the Indent in some way
int cTwoMargins = cMargin * 2;
int indent = (e.Node.Level * cIndentBy) + cMargin;
int iconLeft = indent; // Where to draw parentage lines & icon/checkbox
int textLeft = iconLeft + 16; // Where to draw text
Color leftColour = e.Node.BackColor;
Color textColour = e.Node.ForeColor;
if (Bitfield.IsBitSet(e.State, TreeNodeStates.Grayed))
textColour = Color.FromArgb(255,128,128,128);
// Grad-fill the background
Brush backBrush = new SolidBrush(leftColour);
e.Graphics.FillRectangle(backBrush, itemRect);
// Faint underline along the bottom of each item
Color separatorColor = ColourUtils.Mix(leftColour, Color.FromArgb(255,0,0,0), 0.02);
Pen separatorPen = new Pen(separatorColor);
e.Graphics.DrawLine(separatorPen, itemRect.Left, itemRect.Bottom-1, itemRect.Right, itemRect.Bottom-1);
// Bodged to use Button styles as Treeview styles not available on my laptop...
if (!HideSelection)
{
if (Bitfield.IsBitSet(e.State, TreeNodeStates.Selected) || Bitfield.IsBitSet(e.State, TreeNodeStates.Hot))
{
Rectangle selRect = new Rectangle(textLeft, itemRect.Top, itemRect.Right - textLeft, itemRect.Height);
VisualStyleRenderer renderer = new VisualStyleRenderer((ContainsFocus) ? VisualStyleElement.Button.PushButton.Hot
: VisualStyleElement.Button.PushButton.Normal);
renderer.DrawBackground(e.Graphics, selRect);
// Bodge to make VisualStyle look like Explorer selections - overdraw with alpha'd white rectangle to fade the colour a lot
Brush bodge = new SolidBrush(Color.FromArgb((Bitfield.IsBitSet(e.State, TreeNodeStates.Hot)) ? 224 : 128,255,255,255));
e.Graphics.FillRectangle(bodge, selRect);
}
}
Pen dotPen = new Pen(Color.FromArgb(128,128,128));
dotPen.DashStyle = DashStyle.Dot;
int midY = (itemRect.Top + itemRect.Bottom) / 2;
// Draw parentage lines
if (ShowLines)
{
int x = cMargin * 2;
if (e.Node.Level == 0 && e.Node.PrevNode == null)
{
// The very first node in the tree has a half-height line
e.Graphics.DrawLine(dotPen, x, midY, x, itemRect.Bottom);
}
else
{
TreeNode testNode = e.Node; // Used to only draw lines to nodes with Next Siblings, as in normal TreeViews
for (int iLine = e.Node.Level; iLine >= 0; iLine--)
{
if (testNode.NextNode != null)
{
x = (iLine * cIndentBy) + (cMargin * 2);
e.Graphics.DrawLine(dotPen, x, itemRect.Top, x, itemRect.Bottom);
}
testNode = testNode.Parent;
}
x = (e.Node.Level * cIndentBy) + cTwoMargins;
e.Graphics.DrawLine(dotPen, x, itemRect.Top, x, midY);
}
e.Graphics.DrawLine(dotPen, iconLeft + cMargin, midY, iconLeft + cMargin + 10, midY);
}
// Draw Expand (plus/minus) icon if required
if (ShowPlusMinus && e.Node.Nodes.Count > 0)
{
// Use the VisualStyles renderer to use the proper OS-defined glyphs
Rectangle expandRect = new Rectangle(iconLeft-1, midY - 7, 16, 16);
VisualStyleElement element = (e.Node.IsExpanded) ? VisualStyleElement.TreeView.Glyph.Opened
: VisualStyleElement.TreeView.Glyph.Closed;
VisualStyleRenderer renderer = new VisualStyleRenderer(element);
renderer.DrawBackground(e.Graphics, expandRect);
}
// Draw the text, which is separated into columns by | characters
Point textStartPos = new Point(itemRect.Left + textLeft, itemRect.Top);
Point textPos = new Point(textStartPos.X, textStartPos.Y);
Font textFont = e.Node.NodeFont; // Get the font for the item, or failing that, for this control
if (textFont == null)
textFont = Font;
StringFormat drawFormat = new StringFormat();
drawFormat.Alignment = StringAlignment.Near;
drawFormat.LineAlignment = StringAlignment.Center;
drawFormat.FormatFlags = StringFormatFlags.NoWrap;
string [] columnTextList = text.Split('|');
for (int iCol = 0; iCol < columnTextList.GetLength(0); iCol++)
{
Rectangle textRect = new Rectangle(textPos.X, textPos.Y, itemRect.Right - textPos.X, itemRect.Bottom - textPos.Y);
if (mColumnImageList != null && mColumnImageList[iCol] != null)
{
// This column has an imagelist assigned, so we use the column text as an integer zero-based index
// into the imagelist to indicate the icon to display
int iImage = 0;
try
{
iImage = MathUtils.Clamp(Convert.ToInt32(columnTextList[iCol]), 0, mColumnImageList[iCol].Images.Count);
}
catch(Exception)
{
iImage = 0;
}
e.Graphics.DrawImageUnscaled(mColumnImageList[iCol].Images[iImage], textRect.Left, textRect.Top);
}
else
e.Graphics.DrawString(columnTextList[iCol], textFont, new SolidBrush(textColour), textRect, drawFormat);
textPos.X += mColumnWidthList[iCol];
}
// Draw Focussing box around the text
if (e.State == TreeNodeStates.Focused)
{
SizeF size = e.Graphics.MeasureString(text, textFont);
size.Width = (ClientRectangle.Width - 2) - textStartPos.X;
size.Height += 1;
Rectangle rect = new Rectangle(textStartPos, size.ToSize());
e.Graphics.DrawRectangle(dotPen, rect);
// ControlPaint.DrawFocusRectangle(e.Graphics, Rect);
}
}

Text Wrapping when printing DataGrid? .Net

I'm trying to print a DataGrid in a windows forms app and when the width of the columns is set (it's customizable) too narrow to fit the text it just truncates the text instead of wrapping it. Is there a property in DataGrid that sets text wrapping?
I've added some code to perhaps help with diagnosis of the issue.
private void PrintRow(PointF location, PrintPageEventArgs e)
{
Graphics g = e.Graphics;
PointF curLocation = location;
//Measure the height of one row
SizeF charSize = g.MeasureString(MEASURE_CHAR.ToString(), this.Grid.Font);
float rowHeight = charSize.Height + CELL_PADDING * 2;
//Print the vertical gridline on the left side of the first cell
//Note that we only print the vertical gridlines down to the bottom
//of the last printed row
int maxRowsOnPage = (int)Math.Floor(e.MarginBounds.Height / rowHeight);
int rowsRemaining = this.Grid.Rows.Count - _curRowIdx;
int rowsToPrint = Math.Min(maxRowsOnPage, rowsRemaining);
float bottom = e.MarginBounds.Top + (rowsToPrint * rowHeight);
g.DrawLine(Pens.Black, curLocation.X, e.MarginBounds.Top, curLocation.X, bottom);
DataGridViewRow row = this.Grid.Rows[_curRowIdx];
foreach (QueryField field in _fields)
{
foreach (DataGridViewCell cell in row.Cells)
{
//Exit early if this is not the correct cell
if (this.Grid.Columns[cell.ColumnIndex].HeaderText != field.FieldLabel) continue;
//Calculate where we need to draw the next cell
int maxChars = field.MaxLength > 0 ? field.MaxLength : field.FieldLabel.Length;
SizeF maxSize = g.MeasureString(string.Empty.PadLeft(maxChars, MEASURE_CHAR), this.Grid.Font);
RectangleF boundingRect = new RectangleF(curLocation, maxSize);
//Make sure we don't overshoot the right margin
if (boundingRect.Left >= e.MarginBounds.Right)
{
break;
}
if (boundingRect.Right > e.MarginBounds.Right)
{
boundingRect.Width = boundingRect.Width - (boundingRect.Right - e.MarginBounds.Right);
}
//Get the field value
string fieldValue = string.Empty;
if (cell.Value != null)
{
fieldValue = cell.Value.ToString();
}
//Draw the field value
g.DrawString(fieldValue, this.Grid.Font, Brushes.Black, (RectangleF)boundingRect, sf);
curLocation.X += boundingRect.Width;
curLocation.X += CELL_PADDING;
//Print the vertical gridline between this cell and the next
if (boundingRect.Right <= e.MarginBounds.Right)
{
g.DrawLine(Pens.Black, curLocation.X, e.MarginBounds.Top, curLocation.X, bottom);
}
//Move the current location to the next position
curLocation.X += CELL_PADDING;
}
}
//Draw the top gridline
g.DrawLine(Pens.Black, e.MarginBounds.Left, e.MarginBounds.Top, curLocation.X, e.MarginBounds.Top);
//Draw the bottom gridline
curLocation.Y += charSize.Height;
curLocation.Y += CELL_PADDING;
g.DrawLine(Pens.Black, e.MarginBounds.Left, curLocation.Y, curLocation.X, curLocation.Y);
}
Try this thread. Someone with the exact same problem. Hope it helps!
How to Wrap text in a text box column of datagrid in windows application.

Categories

Resources