Using this:
richTextBox1.AppendText("EMPID: " + "\t\t" + "4001");
richTextBox1.AppendText(System.Environment.NewLine);
richTextBox1.AppendText(System.Environment.NewLine);
richTextBox1.AppendText("EmployeeName: " + "\t\t" + "Taborjakol");
I got this:
How I will perfectly Align it to this:
What you can do is change the tab positions of the RichTextBoxControl.
richTextBox1.SelectionTabs = new int[] { 90, 180, 270, 360 };
richTextBox1.AppendText("EMPID: " + "\t\t" + "4001");
richTextBox1.AppendText(System.Environment.NewLine);
richTextBox1.AppendText(System.Environment.NewLine);
richTextBox1.AppendText("EmployeeName: " + "\t\t" + "Taborjakol");
The SelectionsTab property re-defines the spaces that are used for each tab in the RichTextBox control. You need to experiment with the tab settings to get the best result for your text.
Replace your last line of code with
richTextBox1.AppendText("EmployeeName: " + "\t" + "Taborjakol");
If you dont have to use a richtextbox, you should definetly have a look at the gridview or if you use third party tools like Telerik, DevCraft, ComponentOne and others most of them will have a control called Property Grid that has a layout you might be interested in.
If there is no other way around in using a richtextbox, you have to do the following:
Get a fixed-width font or called monospaced font http://en.wikipedia.org/wiki/Monospaced_font
Evalute the amout of characters which share the same width as a tab (I dont know the number of character have to figure it out yourself with testing)
Get the max length of your text at the left side (your "columnnames" I guess - like "EmployeeName")
Do some math - max length + one tab = x characters
now fill the remaining text at your left side with the neccessary tabs (can be anything from 1 to x) to get the same amout of characters as calculated in 4.
But again a richtextbox isnt the ideal control for this kind of scenario.
Edit:
Here some Code:
public partial class Form1 : Form
{
private const int FetchTestData = 50;
private const int TabCharLength = 5;
public Form1()
{
InitializeComponent();
//With this Fontsettings - 5 chars = 1 Tab - this changes with different fonts
this.richTextBox1.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
var type = typeof(TestData);
var list = GetTestData();
var maxProperty = GetMaxProperty(type);
maxProperty = FillToNext(maxProperty);
var properties = GetProperties(type);
for (var i = 0; i < FetchTestData; i++)
{
var data = list[i];
foreach (var propertyInfo in properties)
{
richTextBox1.AppendText(propertyInfo.Name);
var tabs = GetNumberOfTabs(maxProperty, propertyInfo.Name.Length);
for (var j = 0; j < tabs; j++)
richTextBox1.AppendText("\t");
richTextBox1.AppendText(Convert.ToString(propertyInfo.GetValue(data)));
richTextBox1.AppendText(Environment.NewLine);
}
if (i >= FetchTestData - 1)
continue;
richTextBox1.AppendText(Environment.NewLine);
richTextBox1.AppendText("---------- NEXT DATA ----------");
richTextBox1.AppendText(Environment.NewLine);
}
}
private int GetNumberOfTabs(int maxLength, int textLength)
{
if ((maxLength % TabCharLength) != 0)
maxLength = FillToNext(maxLength);
var difLength = maxLength - textLength;
return (int)(Math.Floor(Convert.ToDouble(difLength / TabCharLength)) + 1);
}
private int FillToNext(int maxLength)
{
return maxLength + (5 - (maxLength % TabCharLength));
}
private PropertyInfo[] GetProperties(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
}
private int GetMaxProperty(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return (from x in GetProperties(type)
select x.Name.Length).Max();
}
private List<TestData> GetTestData()
{
var returnValue = new List<TestData>();
for (int i = 0; i < FetchTestData; i++)
{
returnValue.Add(new TestData()
{
ID = i,
Name = "NameValue " + i,
Description = "DescriptionValue " + i,
PropertyA = "PropertyAValue " + i,
PropertyB = "PropertyBValue " + i,
SomeReallyLongPropertyName = "RandomStuff... " + i
});
}
return returnValue;
}
}
public class TestData
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string SomeReallyLongPropertyName { get; set; }
}
As stated you firstly would want to set the font to a mono-space font, this means that each letter will be the same size.
So you will see something like this:
EEEEEEEEEEE
Rather than
EeEeeiiiiiiiiiiiiiiiiii
Secondly, you could align the text which may improve it slightly:
richTextBox1.SelectAll();
richTextBox1.SelectionAlignment = HorizontalAlignment.Center;
However unless you have to, I would suggest using a different control:
Gridview
Listbox
These are both easy to format, gridview has tabs, and the listbox you can use string.Format when entering the values.
Related
So I'm REALLY new to coding, so I'm learning as I go. I'm doing an assignment for a course, where I have to create a party booking program for a company. The idea is simple, just selected some different options, add them up, and calculate the costs. I have labels that will change and display the integer that the variable is set to, and they work perfectly which would tell me that the variables themselves are indeed getting changed.
However, once I try to add the variables together, it doesn't work.
public partial class AdultPayment : Form
{
public static int ConvertNumberAdult = Convert.ToInt32(Adult.numberAdult);
public static int MealCost = Adult.mealPrice*ConvertNumberAdult;
private static int PrivateRoomCost;
public static int TotalCost = MealCost + CalculateWine + PrivateRoomCost;
public static string DisplayNumberAdult = Convert.ToString(Adult.numberAdult);
private static int CalculateWine { get; set; } = ConvertNumberAdult / 6 * 15;
public AdultPayment()
{
InitializeComponent();
lblAdultConfirmName.Text = Adult.adultContactName;
lblAdultConfirmNumber.Text = Adult.adultContactNumber;
lblAdultConfirmDate.Text = Adult.adultDate;
lblAdultConfirmTime.Text = Adult.adultTime;
lblConfirmNumberOfAdult.Text = Adult.numberAdult.ToString();
lblMealCostTotal.Text = "£"+ MealCost.ToString();
lblCostTotal.Text = "£" + TotalCost.ToString();
if (Adult.adultPrivateRoom == true)
{
PrivateRoomCost = 40;
lblAdultConfirmPrivateRoom.Text = "Yes";
lblPrivateRoomTotal.Text = "£"+ PrivateRoomCost;
}
else
{
PrivateRoomCost = 0;
lblAdultConfirmPrivateRoom.Text = "No";
lblPrivateRoomTotal.Text = "N/A";
}
if(Adult.menuOption == true)
{
lblConfirmMenu.Text = "2 Courses for £15 each";
}
if(Adult.menuOption == false)
{
lblConfirmMenu.Text = "3 Courses for £18 each";
}
if (Adult.addWine == false)
{
CalculateWine = 0;
lblConfirmWineAdded.Text = "No";
lblWineTotal.Text = "N/A";
}
else
{
lblConfirmWineAdded.Text = "Yes";
lblWineTotal.Text = "£"+ CalculateWine.ToString();
}
lblCostTotal.Text = "£" + TotalCost.ToString();
}
}
I have a different form, that allows the users to select their preferences, which works just as I need it to.
The variable that is supposed to add the other variables together is
public static int TotalCost = MealCost + CalculateWine + PrivateRoomCost;
I genuinely am so confused now, and because I'm so new to this I don't know how else to word it in order to find anything on the internet
Any help would be great!
Thanks!
I would like to find the cardinal position of a line (or paragraph) in a pdf which contains a given pattern.
For exemple I can have this problem :
In input, I have a regex (for exemple "Test.*") and a PDF containing a line (or a paragraph) which valid this regex.
I want as an output : the list of Y positions of the lines which validate this regex.
Does anyone have an idea how i can detect that positions ?
Thank you very much.
Eliott
I can have something helpful for you but it is not fully completed. I used to write but I did not finish. you will be able to determine the position of the text. Program return each item in pdf and returns the coordinates.
i Use - itext7 and dotnet core
string[] srcFileNames = { "1.pdf" };
FindTextInPdf("test", srcFileNames);
public void FindTextInPdf(string SearchStr, string[] sources)
{
foreach (var item in sources)
{
if (File.Exists(item))
{
using (PdfReader reader = new PdfReader(item))
using (var doc = new PdfDocument(reader))
{
var pageCount = doc.GetNumberOfPages();
for (int i = 1; i <= pageCount; i++)
{
PdfPage page = doc.GetPage(i);
var box = page.GetCropBox();
var rect = new Rectangle(box.GetX(), box.GetY(), box.GetWidth(), box.GetHeight());
var filter = new IEventFilter[1];
filter[0] = new TextRegionEventFilter(rect);
ITextExtractionStrategy strategy = new FilteredTextEventListener(new TextLocationStrategy(), filter);
var str = PdfTextExtractor.GetTextFromPage(page, strategy);
if (str.Contains(SearchStr) == true)
{
Console.WriteLine("Searched text found in file:[ " + item + " ] page : [ " + i + " ]");
}
foreach (var d in objectResult)
{
Console.WriteLine("Char >"+ d.Text+ " X >"+ d.Rect.GetX()+" font >"+ d.FontFamily + " font size >"+ d.FontSize.ToString()+" space >"+ d.SpaceWidth);**
}
}
}
}
}
class TextLocationStrategy : LocationTextExtractionStrategy
{
public static List<TextMyChunk> objectResult = new List<TextMyChunk>();
public class TextMyChunk
{
public string Text { get; set; }
public Rectangle Rect { get; set; }
public string FontFamily { get; set; }
public float FontSize { get; set; }
public float SpaceWidth { get; set; }
}
public override void EventOccurred(IEventData data, EventType type)
{
if (!type.Equals(EventType.RENDER_TEXT)) return;
TextRenderInfo renderInfo = (TextRenderInfo)data;
IList<TextRenderInfo> text = renderInfo.GetCharacterRenderInfos();
foreach (TextRenderInfo t in text)
{
string letter = t.GetText();
Vector letterStart = t.GetBaseline().GetStartPoint();
Vector letterEnd = t.GetAscentLine().GetEndPoint();
Rectangle letterRect = new Rectangle(letterStart.Get(0), letterStart.Get(1), letterEnd.Get(0) - letterStart.Get(0), letterEnd.Get(1) - letterStart.Get(1));
TextMyChunk chunk = new TextMyChunk();
chunk.Text = letter;
chunk.Rect = letterRect;
chunk.FontFamily = t.GetFont().GetFontProgram().ToString();
chunk.FontSize = t.GetFontSize();
chunk.SpaceWidth = t.GetSingleSpaceWidth();
objectResult.Add(chunk);
}
}
I'm developing a text editor in C#, and I'm trying to make a line count.
private void updateNumberLabel()
{
Point pos = new Point(0, 0);
int firstIndex = Document.GetCharIndexFromPosition(pos);
int firstLine = Document.GetLineFromCharIndex(firstIndex);
pos.X = ClientRectangle.Width;
pos.Y = ClientRectangle.Height;
int lastIndex = Document.GetCharIndexFromPosition(pos);
int lastLine = Document.GetLineFromCharIndex(lastIndex);
int actualLine = Document.GetLineFromCharIndex(actualPos);
pos = Document.GetPositionFromCharIndex(lastIndex);
if (lastLine != actualLine)
{
numberLabel.Text = "";
for (int i = firstLine; i <= lastLine + 1; i++)
{
numberLabel.Text += i + 1 + "\n";
}
}
}
It works fine and adds the number of lines while you write them, but if you delete one, it will only update if you delete or add one more line.
I want make it instantaneous. If you delete one, the count shall be decreased instantaneously.
Maybe this is too easy, but what about that:
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
var lineCount = richTextBox.Lines.Count();
numberLabel.Text = lineCount.ToString();
}
Make sure you assign it to the TextChanged event.
If this is not what you need, please add some more information what you are trying to achieve.
I'm really late, but Lines is an array of string. Just get the length.
richTexBox.Lines.Length.ToString();
I have found one open source and applied it to this problem.
I have confirmed that it works well and have implemented it.
RichTextBox Colums and Row
Simple Code(
The link has a demo source.):
this.rtb.CursorPositionChanged +=
new System.EventHandler(this.rtb_CursorPositionChanged);
this.rtb.SelectionChanged +=
new System.EventHandler(this.rtb_SelectionChanged);
.
.
.
private void rtb_CursorPositionChanged(object sender, System.EventArgs e)
{
int line = rtb.CurrentLine;
int col = rtb.CurrentColumn;
int pos = rtb.CurrentPosition;
statusBar.Text = "Line " + line + ", Col " + col +
", Position " + pos;
}
private void rtb_SelectionChanged(object sender, System.EventArgs e)
{
int start = rtb.SelectionStart;
int end = rtb.SelectionEnd;
int length = rtb.SelectionLength;
statusBar.Text = "Start " + start + ", End " + end +
", Length " + length;
}
namespace Nik.UserControls
{
public class RicherTextBox2 : System.Windows.Forms.RichTextBox
{
public event EventHandler CursorPositionChanged;
protected virtual void OnCursorPositionChanged( EventArgs e )
{
if ( CursorPositionChanged != null )
CursorPositionChanged( this, e );
}
protected override void OnSelectionChanged( EventArgs e )
{
if ( SelectionLength == 0 )
OnCursorPositionChanged( e );
else
base.OnSelectionChanged( e );
}
public int CurrentColumn
{
get { return CursorPosition.Column( this, SelectionStart ); }
}
public int CurrentLine
{
get { return CursorPosition.Line( this, SelectionStart ); }
}
public int CurrentPosition
{
get { return this.SelectionStart; }
}
public int SelectionEnd
{
get { return SelectionStart + SelectionLength; }
}
}
internal class CursorPosition
{
[System.Runtime.InteropServices.DllImport("user32")]
public static extern int GetCaretPos(ref Point lpPoint);
private static int GetCorrection(RichTextBox e, int index)
{
Point pt1 = Point.Empty;
GetCaretPos(ref pt1);
Point pt2 = e.GetPositionFromCharIndex(index);
if ( pt1 != pt2 )
return 1;
else
return 0;
}
public static int Line( RichTextBox e, int index )
{
int correction = GetCorrection( e, index );
return e.GetLineFromCharIndex( index ) - correction + 1;
}
public static int Column( RichTextBox e, int index1 )
{
int correction = GetCorrection( e, index1 );
Point p = e.GetPositionFromCharIndex( index1 - correction );
if ( p.X == 1 )
return 1;
p.X = 0;
int index2 = e.GetCharIndexFromPosition( p );
int col = index1 - index2 + 1;
return col;
}
}
}
Los799
Sorry for answering a "bit" late, I saw this question just now.
But if the problem still stands, here's a simple way to count lines, just use a foreach loop:
int CountOfLines = 1;//1 because min 1 line is always in a text of a control, that has a Text property
foreach (char c in YourText)
{
if (c == '\r' | c == '\n')//these are all equal the ENTER key
{
CountOfLines++;
}
}
You can also use foreach to count characters as well, but with foreach you can choose characters, that you don't want to be counted in the count of characters. For example:
int CountOfCharacters = 0;//0 because by default there are no characters in a textbox or label.
foreach (char c in YourText)
{
if (c != '\t' & c != '\n' & c != '\r')//in this example I want to count only the characters that are not an ENTER or a TAB.
{
CountOfCharacters++;
}
}
Hope this helps you and everybody else, who's reading this, even if it's a bit late answer. :)
Instead of trying to battle with the default rich text box, why don't you try making your own control so you have full control of the text formatting?
After all, if you're developing your own text editor, it would make sense to have text stored and managed in a way that makes sense to you, the developer, instead of trying to fight with a format designed for a slightly different purpose.
Newer solution to this question for WPF applications
DOK1 is a WPF flow document
TX1 is a TextBox control
TX1.Text = DOK1.Blocks.Count.ToString();
I'm encountering an unfamiliar problem with functionality. I think it has something to do with scope of a loop, and server-side code operations/manipulation when rendering a page.
Say I want to repeat a Table Row - each hosts a text input, rows and their textboxes are rendered with values according to content of DATABASE "binded" Data.
Everything works perfectly until more requirements are added - READONLY Attribute And event Key (javascript small validation task).
Otherwise it does work, alternating rows via two separated strings that I "inject" with string format on a condition of if row count is odd vs even, then I tried to filter some of columns to have a keypress event bound to a js function and another attribute as a string.
If the string is empty, then end part of the element "declaration" will be empty
if condition was met, then that string is assigned with value "ReadOnly" and js string is assigned with keypress event "calling a function code".
Here's the code. The situation is weird as style attributes, information of current column, columns names, everything does function as expected but those two READONLY Attribute And event Key (javascript small validation task) that do not.
Render a dynamic Table Code
This is the front code, c# code behind is used mostly (to keep a little code client-side as possible)
`ControlsInteraction.WithTable.Design()`
AND
`ControlsInteraction.WithTable.ExtractData()`
are dealing with dynamic functions of rendering and translation of columns names and values
int count = 0;
bool TblOk = DebugTests.Sesseion.SeSn.Raised(DebugTests.Flag.HT_DB_CPA_Table_init_Complete);
if (TblOk)
{
string TextBxRendr = "";//holds Renderd <TD> base String-code
string AltrnatBgColor;
string NoAttribute = "";
string Js_NumericKprss = "onkeypress=\"return onlN(event)\""
string ReadOnly = "READONLY";
var TimesCol = ALLTablesDataSet.Tables[Tbl1.TableName].Columns;
string DtrawTbl1 = Tbl1.TableName;
ControlsInteraction.WithTable.Design Tbldz =
new ControlsInteraction.WithTable.Design();
ControlsInteraction.WithTable.ExtractData DtExtrct =
new ControlsInteraction.WithTable.ExtractData();
foreach (System.Data.DataRow TimesRow in ALLTablesSet.Tables[DtrawTbl].Rows)
{
AltrnatBgColor= Tbldz.RowsBGColorAlternate(RDE.DataRowToInt(TimesRow, "RecordNum"),true);
altBgColOnly = Tbldz.RowsBGColorAlternate(RDE.DataRowToInt(TimesRow, "RecordNum"), false);
Response.Write(string.Format("<tr {0}>",AltrnatBgColor));
for (int i = 0; i < TimesRow.ItemArray.Length; i++)
{
if (i != (TimesRow.ItemArray.Length - 1))
{
Js_NumericKprss = "onkeypress=\"return onlN(event)\"";
//asking for: current row will Not be read only via its name
if (DtExtrct.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.Comments, DtExtrct.DataRowToInt(TimesRow, "RecordNum")))
Js_NumericKprss = NoAttribute; // same goes with the other manipulation i've needed to implement on each column
TextBxRendr = string.Format(
"<td><input type='text' id=\"{0}_{1}\" value=\"{2} \" style=\"width:50px;{3} border:none; \" class=\"RepTblDataTDs\" {4} {5} \\></td>",
TimesCol[i], TimesRow["RecordNum"], TimesRow[i], AltrnatBgColor,Js_NumericKprss,ReadOnly
);
}
else
{
TextBxRendr = string.Format(
"<td><input type='image' id=\"{0}_{1}\" src=\"images/Save.png\" style=\"width:25px;{2}\" style=\"width:25px\" onclick=\"UbpdateTblCPA(this, {1});\" /></td>",
"img",i + 1, AltrnatBgColor
);
}
Response.Write(TextBxRendr);
count++;
}
}
}
Is injected properly and the read only part READONLY Attribute, and event Key - (javascript small validation task)
Either functions on all or none
What am I doing wrong?
answering my own Question aventually answer is
...well everything , including #Patrics Comment Was Wrong
i can just say put good attention to : how to work with DataTable DataRow, DataTable DataColumns
and the relations for and foreach variables scope
use your visual sudio debugger on every line to check on your codes values
i did not have the time to rename variables but if you need to make a dynamic
html table out of a DB table this is the way
foreach (System.Data.DataRow TimesRow in ALLTablesSet.Tables[DrawTbl].Rows)
{
recordNum = RDE.DataRowToInt(TimesRow, "RecordNum");
AltBgCol = Tbldz.RowsBGColorAlternate(RDE.DataRowToInt(TimesRow, "RecordNum"), true);
altBgColOnly = Tbldz.RowsBGColorAlternate(RDE.DataRowToInt(TimesRow, "RecordNum"), false);
Response.Write(string.Format("<tr {0}>", AltBgCol));
for (int i = 0; i < TimesRow.ItemArray.Length; i++)
{
if (i != (TimesRow.ItemArray.Length - 1))
{
Js_NumericKprss = "onkeypress=\"return onlN(event)\""; ReadOnly = "";
if (RDE.CurrRowIs(TimesRow, HentalDBSchema.HTDB_Cols.TblTimeCPAReport.Comments, i))
{
Js_NumericKprss = ""; ReadOnly = "";
}
else if (RDE.CurrRowIs(TimesRow, HentalDBSchema.HTDB_Cols.TblTimeCPAReport.Fines, i)
|| RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.PhoneExpences, i)
|| RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.SalaryPerDay, i)
|| RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.SalaryPerMonth, i)
|| RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.TotalGrossWages, i)
|| RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.TravelFee, i))
{
ReadOnly = "";
Js_NumericKprss = "onkeypress=\"return onlN(event)\"";
}
else
ReadOnly = "READONLY";
TxtRndr = string.Format("<td><input type='text' id=\"{0}_{1}\" value=\"{2} \" style=\"width:50px;{3} border:none; \" class=\"RepTblDataTDs\" {5} {6} \\></td>{4}", TimesCol[i], TimesRow["RecordNum"], TimesRow[i], altBgColOnly, Environment.NewLine + "\t\t\t", Js_NumericKprss, ReadOnly);
}
else
{
TxtRndr = string.Format("<td><input type='image' id=\"{0}_{1}\" src=\"images/Save.png\" style=\"width:25px;{3}\" style=\"width:25px\" onclick=\"UbpdateTblCPA(this, {1});\" /></td>{4}", "imgBut", i + 1, TimesRow[i], altBgColOnly, Environment.NewLine + "\t\t\t");
}
Response.Write(TxtRndr);
count++;
}
}
i am adding all researches i have made to be more easy on the data extraction and some more methods i have worked on so if u like to use it feel free to ...
public class ControlsInteraction
{
public class WithDDL
{
public class GetSelVal
{
public string AsString(DropDownList DDLToCollectValusFrom)
{
return DDLToCollectValusFrom.SelectedValue;
}
public int AsInt(DropDownList DDLToCollectValusFrom)
{
if(DDLToCollectValusFrom.SelectedValue != null)
return Convert.ToInt32(DDLToCollectValusFrom.SelectedValue);
return 666;
}
}
public List<string> GetListItems_Values(DropDownList DDLToCollectValusFrom)
{
List<string> LST_DDLValues = new List<string>();
foreach (ListItem item in DDLToCollectValusFrom.Items)
{
LST_DDLValues.Add(item.Value);
}
return LST_DDLValues;
}
public List<string> GetListItems_Text(DropDownList DDLToCollectTextFrom)
{
List<string> LST_DDLTEXT = new List<string>();
foreach (ListItem item in DDLToCollectTextFrom.Items)
{
LST_DDLTEXT.Add(item.Text);
}
return LST_DDLTEXT;
}
}
public static class WithPlcHldr
{
public static void AddCtrl(PlaceHolder PlcHldrID, Control CntrID)
{
PlcHldrID.Controls.Add(CntrID);
}
}
public class WithTable
{
public class Design
{
public string RowsBGColorAlternate(int RowCounter, bool AddWithStyleAsStandAlone = false)
{
string BgCol = ""; bool bgclaltrnator;
if (RowCounter > 0)
{
RowCounter++;
bgclaltrnator = (RowCounter % 2) == 0;
if (bgclaltrnator)
BgCol = "#70878F";
else BgCol = "#E6E6B8";
}
if (AddWithStyleAsStandAlone)
return string.Format("style=\"background-color:{0};\"", BgCol);
return string.Format("background-color:{0};", BgCol);
}
}
public class ExtractData
{
public string ColumnValueFromCurrRow(DataRow DtRow, string RequestedColName)
{
return "";
}
public string DataRows_ColumnToString(DataRow Data_RowToActOn, string keyColName)
{
var tmp = Data_RowToActOn[keyColName];
return Data_RowToActOn[keyColName].ToString();
}
public int DataRowToInt(DataRow Data_RowToActOn, string keyColName)
{
string tmp = Data_RowToActOn[keyColName].ToString();
return Convert.ToInt32(tmp);
}
public bool CurrColumnIs(DataColumn Data_RowToQuestion, string ColumnName)
{
string tmp = Data_RowToQuestion.ToString();
return tmp == ColumnName;
}
public bool CurrRowIs(DataRow Data_RowToQuestion, string RowName, int CurrIndex)
{
string ColsName = Data_RowToQuestion.Table.Columns[CurrIndex].ToString();
return ColsName == RowName;
//this is curent value - by index
//string currentColumn = Data_RowToQuestion.ItemArray[CurrIndex].ToString();
}
}
}
}
I want to Display an icon in the particular cell.
I am using this code. I have commented where i want to display the icon:
string lastScripDate = this.GetLastScripDate(sFolderPath, pb);
string sQuery = "select * from database";
DataTable table = new DataTable();
table = this.Retrieve_Data(sQuery, "database");
pb.Maximum = table.Rows.Count;
pb.Value = 0;
double num = 0.0;
double num2 = 0.0;
double num3 = 0.0;
double num4 = 0.0;
if (table.Rows.Count > 0)
{
for (int i = 0; i < table.Rows.Count; i++)
{
Application.DoEvents();
dgv.Rows.Add();
dgv.Rows[i].Cells["Sname"].Value = table.Rows[i]["Symbol"].ToString();
dgv.Rows[i].Cells["clsprice"].Value = table.Rows[i]["SCRIP"].ToString();
string str3 = table.Rows[i]["TradeType"].ToString();
dgv.Rows[i].Cells["trd"].Value = str3;
string str4 = str3;
if (str4 != null)
{
if (!(str4 == "p"))
{
if (str4 == "q")
{
goto Label_01DD;
}
}
else
{
dgv.Rows[i].Cells["trd"].Style.ForeColor = Color.Green;///////I Want to Display Icon in this Cell(Up.Ico)
}
}
goto Label_020B;
Label_01DD:
dgv.Rows[i].Cells["Trade"].Style.ForeColor = Color.Red;///////////////An Want to Display Icon in this Cell also(Down.Ico
Label_020B:
dgv.Rows[i].Cells["date"].Value = table.Rows[i]["TDate"].ToString();
num = Convert.ToDouble(table.Rows[i]["CPrice"]);
dgv.Rows[i].Cells["tp"].Value = string.Format("{0:0.00}", num);
num2 = Convert.ToDouble(table.Rows[i]["Price"]);
dgv.Rows[i].Cells["tp"].Value = string.Format("{0:0.00}", num2);
num3 = Convert.ToDouble(table.Rows[i]["Loss"]);
dgv.Rows[i].Cells["sl"].Value = string.Format("{0:0.00}", num3);
try
{
num4 = Convert.ToDouble(table.Rows[i]["Ratio"]);
dgv.Rows[i].Cells["Ratio"].Value = string.Format("{0:0.00}", num4);
}
catch
{ }
pb.Value++;
}
if (pb.Value == pb.Maximum)
{
pb.Value = pb.Minimum;
}
return true;
}
return false;
One way to acheive this would be to add DataGridViewImageColumn and then set icon to that cell. Here is a sample
dataGridView1.Columns.Add(new DataGridViewImageColumn());
dataGridView1.Rows.Add(2);
DataGridViewImageCell cell = (DataGridViewImageCell)dataGridView1.Rows[0].Cells[0];
Icon ic = new Icon("icon.ico");
cell.Value = ic;
1 - create some icons inside a property class
Example
public static class EIcons
{
/// <summary>
/// NULL
/// </summary>
public static readonly Icon NOICON = new Icon("Icon/null.ico");
/// <summary>
/// NEW
/// </summary>
public static readonly Icon NEW = new Icon("Icon/new.ico");
}
2 - Create a property for your datagrid, that contains strings, or int, and also ICONS objects.
The constructor must always initialize your icon to something consistent.
public class GridProperty01
{
/// <summary>
/// CONSTRUCTOR - factory initialization
/// </summary>
public GridProperty01()
{
ID = 0;
NewValue = string.Empty;
Alert = EIcons.NOICON; // solid icon initialization. Create transparent icon if you wish...
}
public int ID { get; set; }
public string NewValue { get; set; }
public Icon Alert { get; set; } // for icon
}
3 - Create a list of data and assign to your icon property the icon you need. At last bind the list to your datagrid, and refresh.
All this code must be put inside a button of SEARCH for example, or inside a method that update the gridview..
// GET - data for datagridview
List<GridProperty01> tempList = new List<GridProperty01>();
for (int jj = 0; jj < 3; ++jj) {
// INIT
GridProperty01 tempObj = new GridProperty01();
// GET - data
tempObj.ID = jj; // your code...
tempObj.NewValue = "xxx"; // your code...
tempObj.Alert = EIcons.NEW; // an icon...
// SET - insert row to list
tempList.Add(tempObj);
}
// SET - assign list to your gridview
dataGridView01.DataSource = tempList;
// SET - refresh
dataGridView01.Update();
dataGridView01.Refresh();
I suppose that's enough.
In addition, if you plan to SORT the Icon column when the column header has been clicked, create an Icon Text property, that contains different "text" accordingly to your Icon property. At the sort use this string to sort the rows of the datagrid. In this case, you should have:
// example code..
Alert = EIcons.NEW;
AlertText = "new";
Alert = EIcons.NOICON;
AlertText = "noicons";
you can make it by using DataGridViewImageColumn