Before I had a question about (specific distance (space) between columns of drop down list) and I received my answer like below code, my problem is the spaces between columns will be fill by '_', when I change that to something like " ", it does not work and columns are beside each other, I need white space between columns, how can I do that?
protected void ddlStack_Load(object sender, EventArgs e)
{
var all = from o in _DataContext.tblDocuments
orderby o.DocumentNo
select o;
int maxs = 0;
foreach (tblDocuments v in all)
{
if (v.DocumentNo.Length > maxs)
maxs = v.DocumentNo.Length;
}
foreach (tblDocuments vv in all)
{
string doctitle = vv.DocumentNo;
for (int i = vv.DocumentNo.Length; i < maxs + 2; i++)
{
doctitle += '_';
}
doctitle += " | ";
doctitle += vv.DocID;
ddlStack.Items.Add(new ListItem(doctitle, vv.vendorID.ToString()));
}
}
You should use instead of a regular " " (space) and then use HtmlDecode before creating the ListBoxItem...
Try something like this:
foreach (tblDocuments vv in all)
{
string doctitle = vv.DocumentNo;
for (int i = vv.DocumentNo.Length; i < maxs + 2; i++)
{
doctitle += " ";
}
doctitle += " | ";
doctitle += vv.DocID;
// Use HtmlDecode to correctly show the spaces
doctitle = HttpUtility.HtmlDecode(doctitle );
ddlStack.Items.Add(new ListItem(doctitle, vv.vendorID.ToString()));
}
Related
I'm doing on a GUI to extract position X and Y from GCode by using Regex and print it on richTextBox.
private void button1_Click(object sender, EventArgs e)
{
TextReader read = new System.IO.StringReader(richTextBox1.Text);
int rows = richTextBox1.Lines.Length;
Console.WriteLine(rows);
string[] text = new string[rows];
for (int r = 0; r < rows; r++)
{
text[r] = read.ReadLine();
if (text[r] != null)
{
Match posX = Regex.Match(text[r], #"X([0-9\.]+)");
Match posY = Regex.Match(text[r], #"Y([0-9\.]+)");
GroupCollection posXGroup = posX.Groups;
GroupCollection posYGroup = posY.Groups;
Console.WriteLine(posXGroup[1] + "\t" + posYGroup[1] + "\n");
richTextBox2.Text = (posXGroup[1] + "\t" + posYGroup[1] + "\n");
}
}
}
My GCode:
N65 G2 X21.5091 Y15.5209 Z0.0000 I0.0277 J-0.7392
N120 G2 X21.5280 Y18.0069 Z0.0000 I0.0255 J-0.7476
N210 G2 X21.5968 Y15.0534 Z0.0000 I-0.0483 J-1.2184
N230 G2 X21.6745 Y17.4894 Z0.0000 I0.0473 J-1.2560
My problem is printing the result to richTextBox. It prints only the value of last line: 21.6745 17.4894 but not positions in 3 lines above it. While the console prints successfully. Can someone help me with this?
Quick fix is to concatenate the text:
richTextBox2.Text += (posXGroup[1] + "\t" + posYGroup[1] + "\n");
A better solution is never to use String Concatenation as that will put pressure on the GC as each concatenate adds to the Heap. Instead use a StringBuilder:
private void button1_Click(object sender, EventArgs e)
{
TextReader read = new System.IO.StringReader(richTextBox1.Text);
int rows = richTextBox1.Lines.Length;
Console.WriteLine(rows);
string[] text = new string[rows];
var sb = new StringBuilder();
for (int r = 0; r < rows; r++)
{
text[r] = read.ReadLine();
if (text[r] != null)
{
Match posX = Regex.Match(text[r], #"X([0-9\.]+)");
Match posY = Regex.Match(text[r], #"Y([0-9\.]+)");
GroupCollection posXGroup = posX.Groups;
GroupCollection posYGroup = posY.Groups;
Console.WriteLine(posXGroup[1] + "\t" + posYGroup[1] + "\n");
sb.Append(posXGroup[1]);
sb.Append("\t");
sb.Append(posYGroup[1]);
sb.Append("\n");
}
}
richTextBox2.Text = sb.ToString();
}
To see why this is happening put a breakpoint on the line richTextBox2.Text = then step through the code pressing F10, each iteration of the loop will reset the richTextBox2.Text's value.
You're assigning over the top. You need to assign by concatenating to append the text. It doesn't matter if the text has new lines. Assignment = will set the variable to the Text property. Addition assignment operator += will concatenate.
i want to concat(add) a string over an existing item here is the code:
private void button4_Click(object sender, EventArgs e)
{
double total = 0;
double[] prices = {0.5, 1.0, 1.5, 3.0, 2.5, 2.0};
CheckBox[] boxes = { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6 };
listBox2.Items.Add(textBox1.Text + " : ");
for (int i=0;i<boxes.Length ;i++)
{
if (boxes[i].Checked==true)
{
total += prices[i];
listBox2.Items.Add(boxes[i].Text+" "); //it adds a new item
}
}
the problem is with the output , every time it adds a new item i just want to add this line boxes[i].Text+" " , to the same item
thank you.
What do you mean by:
to the same item
Do you want to add it all to this one? listBox2.Items.Add(textBox1.Text + " : ");
If so could you not just do this:
string name = textBox1.Text + " : ";
for (int i=0; i < boxes.Length; i++)
{
if (boxes[i].Checked == true)
{
total += prices[i];
name += boxes[i].Text + " ";
}
}
listBox2.Items.Add(name);
You should use the following command listbox2.items[0]+=boxes[i].Text+" " with 0 being the index of the item you want to concatenate the string with.Because listbox2.items.Add will just keep adding items to your Listbox.
Best Regards.
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();
protected void ReadHtmlTable(string patientName, string startHour, string startMinute, int rowspan)
{
for(int i = 0; i <= tableAppointment.Rows.Count - 1; i++)
{
for(int j = 0; j <= tableAppointment.Rows[i].Cells.Count - 1; j++)
{
if(tableAppointment.Rows[i].Cells[j].InnerHtml.Trim() == startHour)
{
if(tableAppointment.Rows[i].Cells[j + 1].InnerHtml.Trim()== startMinute)
{
tableAppointment.Rows[i].Cells[j + 2].InnerText = patientName;
tableAppointment.Rows[i].Cells[j + 2].RowSpan = rowspan;
tableAppointment.Rows[i].Cells[j + 2].Style.Add("color", "green");
tableAppointment.Rows[i].Cells[j + 2].Style.Add("background", "green");
}
}
}
}
}
Above code is my server side code which executes on OnSaveStateComplete(EventArgs e) event . i am reading my html table in c#. when i check its first cell second cell text then its give result like this "\r\n\t\t\t\t\t\t\t\t\t08:00\r\n\t\t\t\t\t\t\t\t" .I have use trim at end but not work.
Try this
string str = "\r\n\t\t\t\t\t\t\t\t\t08:00\r\n\t\t\t\t\t\t\t\t".Trim('\t', '\r', '\n');
You should be able to RegEx it out of there with
RegEx.Replace(tableAppointment.Rows[i].Cells[j + 1].InnerHtml, "\\s+", "");
The Regex.Replace method at MSDN. The example there also has dealing with white space.
I'm trying to do this and it is a bit confusing for me.
Basically the scenario is like this, I'm getting an XML from a 3rd party application with available dates for booking, for each day there are types of rooms the person can choose, single, double, etc.
Each hostel will return me an unknown number of room types. But dont get too confused with this.
The thing is simple I just need to add an unknown number of dropdownlists (or HTML Select) with the numbers of persons to book for. Now because I don't know how many of those dropdowns I will have I need to add them programatically inside a "for int i=0; i
How can I add an unknownn number of dropdownlists programatically to a page and retrieve the selected values with c# on submit?
The last column on the screenshot
http://i.stack.imgur.com/37chw.png
Update:
I'm creating the code from the xml results as a string that will print as html code:
XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc.LoadXml(getPrices());
XmlNodeList prices = xmlDoc.GetElementsByTagName("RoomType");
string[] bookingDates = new string[Convert.ToInt32(Request.QueryString["nights"])];
string[] bookingDays = new string[Convert.ToInt32(Request.QueryString["nights"])];
bookingDates[0] = Request.QueryString["date"].ToString();
string[] dateArray = Request.QueryString["date"].ToString().Split('-');
DateTime initialDate = new DateTime(Convert.ToInt32(dateArray[0]), Convert.ToInt32(dateArray[1]), Convert.ToInt32(dateArray[2]));
bookingDays[0] = initialDate.DayOfWeek.ToString();
for (int z = 1; z < bookingDates.Length; z++)
{
DateTime nextDay = initialDate.AddDays(z);
string month = nextDay.Month.ToString();
string day = nextDay.Day.ToString();
if (day.Length == 1)
{
day = "0" + day;
}
if (month.Length == 1)
{
month = "0" + month;
}
bookingDates[z] = nextDay.Year + "-" + month + "-" + day;
bookingDays[z] = nextDay.DayOfWeek.ToString();
}
string pricesHeader = "<table width='100%'>";
pricesHeader += "<tr><td>Room Type</td>";
for (int x = 0; x < bookingDates.Length; x++)
{
string[] bookingDay = bookingDates[x].Split('-');
pricesHeader += "<td align='center'>" + bookingDays[x].Substring(0, 3) + "<br>" + bookingDay[2] + "</td>";
}
pricesHeader += "<td>Persons</td></tr>";
string pricesContent = "<tr>";
int dropNumber = 1;
foreach (XmlElement node in prices)
{
XmlNodeList roomTypeDescriptionN = node.GetElementsByTagName("roomTypeDescription");
string roomTypeDescriptionS = roomTypeDescriptionN[0].InnerText;
pricesContent += "<td>" + roomTypeDescriptionS + "</td>";
XmlNodeList priceN = node.GetElementsByTagName("price");
string priceS = priceN[0].InnerText;
XmlNodeList currencyN = node.GetElementsByTagName("currency");
string currencyS = currencyN[0].InnerText;
if (currencyS == "EUR")
{
currencyS = "&euro";
}
string avDates = "";
XmlNodeList availableDatesN = node.GetElementsByTagName("date");
int dateNumber = 0;
foreach (XmlElement avDate in availableDatesN)
{
avDates += availableDatesN[dateNumber].InnerText + ",";
dateNumber++;
}
for (int c = 0; c < bookingDates.Length; c++)
{
if (avDates.Contains(bookingDates[c]))
{
pricesContent += "<td>" + priceS + currencyS + "</td>";
}
else
{
pricesContent += "<td><center>X</center></td>";
}
}
pricesContent += "<td><select runat=server name='pers" + dropNumber + "' id='pers" + dropNumber + "'>" +
"<option>0</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option></select></td></tr>";
dropNumber++;
}
pricesLabel.Text = pricesHeader + pricesContent + "</table>";
I know that doing that and adding the runat=server won't help on my control, there is where my main problem is now, how to add the code on the html to be able to get the dropdownlist selected value later with c#. Can I do that with Request.Form ? was trying but so far I couldnt do it.
You can use the Repeater Class for generation of controls
You can also use the Request.Form Collection for obtaining of user's choice
You can use List for saving your created dropdownlists. On submit, you can read the data from your list.
List<DropDownList> ddlList = new List<DropDownList>{};
for(int i=0;i<count;i++)
{
//add control to page
ddlList.items.add(YourNewlyCreatedDdl);
}
for (int i = 0; i < 5; i++)
{
DropDownList ddl = new DropDownList();
ddl.ID=string.Format("ddl_{0}",i);
this.form1.Controls.Add(ddl);
}
This creates 5 empty DropDownLists.
You will need to rebuild and repopulate the controls on each postback in order for ASP to recognise their values.