Making a picture box become visible / invisible on a certain integer? (C#) - c#

I was wondering how I would make a picture box become invisible or visible when a certain integer matches.
My program revolves around 2 players going around a board, and when they add there 2 Di up, they will move the amount of spaces.
My problem being, My friend and I have no idea what is wrong with the current code we have, it throws no errors which baffles him, especially myself.
I've made it so my program add's the Di up on every roll, and add's it to the integer.
Anyone have any idea's on whats wrong? If not, a better approach?
Code
private void SelectPos(PictureBox pic)
{
PictureBox[] numbers = { P1_1, P1_2, P1_3, P1_4, P1_5, P1_6, P1_7, P1_8, P1_9, P1_10, P1_11, P1_12, P1_13, P1_14, P1_15, P1_16, P1_17, P1_18, P1_19, P1_20, P1_21, P1_22, P1_23, P1_24, P1_25, P1_26, P1_27, P1_28, P1_29, P1_30, P1_31, P1_32, P1_33, P1_34, P1_35, P1_36, P1_37, P1_38, P1_39, P1_40, P1_41, P1_42, P1_43, P1_44, P1_45, P1_46, P1_47, P1_48, P1_49 };
for (int i = 0; i < numbers.Length; i++)
{
if (pic == numbers[i])
{
numbers[i].Visible = true;
MessageBox.Show("k");
}
{
numbers[i].Visible = false;
MessageBox.Show("l");
}
}
}
private void bunifuFlatButton1_Click(object sender, EventArgs e)
{
Roll();
System.Threading.Thread.Sleep(100);
Roll2();
Goes_Num.Text = (int.Parse(Goes_Num.Text) + 1).ToString();
if (Convert.ToInt32(Goes_Num.Text) % 2 == 0)
{
WhichPlayer.Text = "Player 2";
P2_Number.Text = (int.Parse(P2_Number.Text) + 1).ToString();
int p2Int = Convert.ToInt32(P2_Pos.Text);
P2_Pos.Text = (p2Int + dice + dice2).ToString();
}
else if (Convert.ToInt32(Goes_Num.Text) % 2 != 0)
{
WhichPlayer.Text = "Player 1";
P1_Number.Text = (int.Parse(P1_Number.Text) + 1).ToString();
int p1Int = Convert.ToInt32(P1_Pos.Text);
P1_Pos.Text = (p1Int + dice + dice2).ToString();
int P1 = (Convert.ToInt32(P1_Pos.Text));
SelectPos(P1_1);
/*switch (P1)
{
case 1:
P1_1.Visible = true;
break;
case 2:
P1_2.Visible = true;
break;
}*/
/*String[] hi = { "1", "2" };
for (int i = 0; i < hi.Length; i++)
{
var visible = p1
if(visible == hi[i])
{
hi[i].Visible = true;
}
else
{
hi[i].Visible = false;
}
}*/
}
}
(P1-1 all the way to P1-49 are images)
Thanks,
James

It looks like you're trying to pass an int to your SelectPos function but it expects a PictureBox. You could fix this doing something similar to the following:
private void SelectPos(int pic)
{
PictureBox[] numbers = { P1_1, P1_2, P1_3, P1_4, P1_5, P1_6, P1_7, P1_8, P1_9, P1_10, P1_11, P1_12, P1_13, P1_14, P1_15, P1_16, P1_17, P1_18, P1_19, P1_20, P1_21, P1_22, P1_23, P1_24, P1_25, P1_26, P1_27, P1_28, P1_29, P1_30, P1_31, P1_32, P1_33, P1_34, P1_35, P1_36, P1_37, P1_38, P1_39, P1_40, P1_41, P1_42, P1_43, P1_44, P1_45, P1_46, P1_47, P1_48, P1_49 };
//Set all picture boxes to be not visible
for (int i = 0; i < numbers.Length; i++)
{
numbers[i].Visible = false;
}
//Set the picture at the given index to visible
numbers[pic].Visible = true;
}
private void bunifuFlatButton1_Click(object sender, EventArgs e)
{
Roll();
System.Threading.Thread.Sleep(100);
Roll2();
Goes_Num.Text = (int.Parse(Goes_Num.Text) + 1).ToString();
if (Convert.ToInt32(Goes_Num.Text) % 2 == 0)
{
WhichPlayer.Text = "Player 2";
P2_Number.Text = (int.Parse(P2_Number.Text) + 1).ToString();
int p2Int = Convert.ToInt32(P2_Pos.Text);
P2_Pos.Text = (p2Int + dice + dice2).ToString();
}
else if (Convert.ToInt32(Goes_Num.Text) % 2 != 0)
{
WhichPlayer.Text = "Player 1";
P1_Number.Text = (int.Parse(P1_Number.Text) + 1).ToString();
int p1Int = Convert.ToInt32(P1_Pos.Text);
P1_Pos.Text = (p1Int + dice + dice2).ToString();
int P1 = (Convert.ToInt32(P1_Pos.Text));
SelectPos(P1);
}
}
You may have to manipulate the value of pic so that it is within the bounds of the array (0-48). For example if pic is between 1 and 49 you would need to subtract 1: numbers[pic-1]. Without seeing your whole program I can't tell you exactly how that part of the code would look but it should be pretty easy to figure out. If you aren't familiar with arrays and indexing check out this link or just Google C# Arrays.
As a side note it would be better to the numbers array as a private member of the class this code is in. Unless the values in the array change there's no point in building the array every time the method is called.

Complete code:
private void SelectPos(int pic)
{
PictureBox[] numbers = { P1_1, P1_2, P1_3, P1_4, P1_5, P1_6, P1_7, P1_8, P1_9, P1_10, P1_11, P1_12, P1_13, P1_14, P1_15, P1_16, P1_17, P1_18, P1_19, P1_20, P1_21, P1_22, P1_23, P1_24, P1_25, P1_26, P1_27, P1_28, P1_29, P1_30, P1_31, P1_32, P1_33, P1_34, P1_35, P1_36, P1_37, P1_38, P1_39, P1_40, P1_41, P1_42, P1_43, P1_44, P1_45, P1_46, P1_47, P1_48, P1_49 };
//Set all picture boxes to be not visible
for (int i = 0; i < numbers.Length; i++)
{
numbers[i].Visible = false;
}
//Set the picture at the given index to visible
numbers[pic].Visible = true;
}
private void SelectPos2(int pic2)
{
PictureBox[] numbers2 = { P2_1, P2_2, P2_3, P2_4, P2_5, P2_6, P2_7, P2_8, P2_9, P2_10, P2_11, P2_12, P2_13, P2_14, P2_15, P2_16, P2_17, P2_18, P2_19, P2_20, P2_21, P2_22, P2_23, P2_24, P2_25, P2_26, P2_27, P2_28, P2_29, P2_30, P2_31, P2_32, P2_33, P2_34, P2_35, P2_36, P2_37, P2_38, P2_39, P2_40, P2_41, P2_42, P2_43, P2_44, P2_45, P2_46, P2_47, P2_48, P2_49 };
//Set all picture boxes to be not visible
for (int i = 0; i < numbers2.Length; i++)
{
numbers2[i].Visible = false;
}
//Set the picture at the given index to visible
numbers2[pic2].Visible = true;
}
private void bunifuFlatButton1_Click(object sender, EventArgs e)
{
Roll();
System.Threading.Thread.Sleep(100);
Roll2();
Goes_Num.Text = (int.Parse(Goes_Num.Text) + 1).ToString();
if (Convert.ToInt32(Goes_Num.Text) % 2 == 0)
{
WhichPlayer.Text = "Player 2";
P2_Number.Text = (int.Parse(P2_Number.Text) + 1).ToString();
int p2Int = Convert.ToInt32(P2_Pos.Text);
P2_Pos.Text = (p2Int + dice + dice2).ToString();
int P2 = (Convert.ToInt32(P2_Pos.Text));
SelectPos2(P2);
}
else if (Convert.ToInt32(Goes_Num.Text) % 2 != 0)
{
WhichPlayer.Text = "Player 1";
P1_Number.Text = (int.Parse(P1_Number.Text) + 1).ToString();
int p1Int = Convert.ToInt32(P1_Pos.Text);
P1_Pos.Text = (p1Int + dice + dice2).ToString();
int P1 = (Convert.ToInt32(P1_Pos.Text));
SelectPos(P1);
}
}

Related

How to delete an item row in C# in a 2D array in forms

Hello I was wondering how can I delete a row from the array in C# forms using a button, like you write which line# you want to delete and then pressing the button will delete that item from the list. The idea is to delete a row using "button 2" that reads the number written in a "textbox". And also how to show a warning message if the row doesn't exist. I cant use the "list<>" or "grid thing". Thanks if any of you have a little hand to lend me.
`
public partial class Form1 : Form
{
int pos = 0;
int counter = 0;
string[,] sales = new String[50, 5];
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string product;
double price, subtotal, total;
int qty;
textBox1.BackColor = Color.White;
if (textBox1.Text == "")
{
textBox1.BackColor = Color.Red;
textBox1.Focus();
MessageBox.Show("MISSING PRODUCT!!!");
return;
}
textBox2.BackColor = Color.White;
if (textBox2.Text == "")
{
textBox2.BackColor = Color.Red;
textBox2.Focus();
MessageBox.Show("MISSING PRODUCT!!!");
return;
}
textBox3.BackColor = Color.White;
if (textBox3.Text == "")
{
textBox3.BackColor = Color.Red;
textBox3.Focus();
MessageBox.Show("MISSING PRODUCT!!!");
return;
}
product = textBox1.Text;
price = double.Parse(textBox2.Text);
qty = int.Parse(textBox3.Text);
subtotal = price * qty;
sales[pos, 0] = pos.ToString();
sales[pos, 1] = product;
sales[pos, 2] = price.ToString();
sales[pos, 3] = qty.ToString();
sales[pos, 4] = subtotal.ToString();
pos++;
textBox5.Text = "";
total = 0;
for (int i = 0; i < sales.GetLength(0); i++)
{
textBox5.Text += sales[i, 0] + " " + sales[i, 1] + " " + sales[i, 2] + " " + sales[i, 3] + " " + sales[i, 4] + " " + "\r\n";
//<>
if (sales[i, 4] != null)
{
total += int.Parse(sales[i, 4]);
}
}
textBox4.Text = total.ToString();
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox1.Focus();
}
private void button2_Click(object sender, EventArgs e)
{
// what to put here
}
}
`
Context
I'm going to give you two answers here as you aren't clear on whether or not you are required to use an array instead of a List<>. I'm also a little unsure about what exactly you're asking for, as you haven't given any examples of what you hope the output would be, or anything like that, so I apologize if I totally miss the mark. Just let me know and I'll change my answer to match what you're asking more appropriately :)
Using an array
private void button2_Click(object sender, EventArgs e)
{
//Checks to see if the desired row to delete exists
if(sales[pos][0] is null)
{
//Lets the user know the index is already empty
MessageBox.Show("Index has no product listed.");
return;
}
//Loops through each item at the pos index
for(int i = 0; i < sales.GetLength(1); i++)
{
//remove
sales[pos][i] = null;
}
/*******************************************************
* I'm unsure if you would want to drop the index of all
* of the arrays with a larger index number down one, so
* this next bit of code will do this, but if you don't
* want this functionality, just ignore this.
********************************************************/
//Loops through every index from pos to the second to last index
for(int i = pos; i < sales.GetLength(0) - 1; i++)
{
//Loops through every index of a product
for(int j = 0; j < sales.GetLength(1); j++)
{
//Sets current row to the value in the next
sales[i][j] = sales[i+1][j];
}
}
}
Using a List<>
/*****************************************************
* I've changed the name of the variable to pascal case
* as this is Microsoft's documentation standard.
* This also shows how you would need to change the
* declaration of the Sales object.
*****************************************************/
List<List<string>> Sales = new List<List<string>>();
private void button2_Click(object sender, EventArgs e)
{
//Checks if the index is out of bounds of the list.
if(pos > Sales.Count() - 1)
{
//Lets the user know the index out of bounds
MessageBox.Show("Index is out of bounds.");
return;
}
//Remove the product at the selected index
Sales.RemoveAt(pos);
}
Products
I notice that you seem to be trying to make a list of products to be sold. I would recommend that you create a Product class, which holds all of the information that a product has. A quick mock up of that could look something like this:
public class Product
{
/**********************************************************
* If you are unfamiliar with how properties work,
* I recommend looking into them more, but quick, simplified
* explanation is they are just variables you access from
* other classes that have access to this one by
* saying, in this case, Product.AttributeOne, and you
* can even set it by writing Product.AttributeOne = "foo";
**********************************************************/
public string AttributeOne { get; set; }
public string AttributeTwo { get; set; }
public string AttributeThree { get; set; }
public string AttributeFour { get; set; }
public string AttributeFive { get; set; }
}
Using this class could simplify other code you have, and make your array/list one dimensional. I would highly recommend making products an object, just as it would give you more functionality for a lot less code. I'll show you how the code for button1_Click and button2_Click() would look like with this change
public partial class Form1 : Form
{
int pos = 0;
int counter = 0;
List<Product> Sales = new List<Product>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string product;
double price, subtotal, total;
int qty;
textBox1.BackColor = Color.White;
if (textBox1.Text == "")
{
textBox1.BackColor = Color.Red;
textBox1.Focus();
MessageBox.Show("MISSING PRODUCT!!!");
return;
}
textBox2.BackColor = Color.White;
if (textBox2.Text == "")
{
textBox2.BackColor = Color.Red;
textBox2.Focus();
MessageBox.Show("MISSING PRODUCT!!!");
return;
}
textBox3.BackColor = Color.White;
if (textBox3.Text == "")
{
textBox3.BackColor = Color.Red;
textBox3.Focus();
MessageBox.Show("MISSING PRODUCT!!!");
return;
}
product = textBox1.Text;
price = double.Parse(textBox2.Text);
qty = int.Parse(textBox3.Text);
subtotal = price * qty;
Sales.ElementAt(pos).AttributeOne = pos.ToString();
Sales.ElementAt(pos).AttributeTwo = product;
Sales.ElementAt(pos).AttributeThree = price.ToString();
Sales.ElementAt(pos).AttributeFour = qty.ToString();
Sales.ElementAt(pos).AttributeFive = subtotal.ToString();
pos++;
textBox5.Text = "";
total = 0;
for (int i = 0; i < Sales.Count; i++)
{
textBox5.Text += Sales.ElementAt(i).AttributeOne + " " + Sales.ElementAt(i).AttributeTwo + " " + Sales.ElementAt(i).AttributeThree + " " + Sales.ElementAt(i).AttributeFour + " " + Sales.ElementAt(i).AttributeFive + " " + "\r\n";
//<>
if (Sales.ElementAt(i).AttributeFive != null)
{
total += int.Parse(sales[i, 4]);
}
}
textBox4.Text = total.ToString();
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox1.Focus();
}
private void button2_Click(object sender, EventArgs e)
{
//Checks if the index is out of bounds of the list.
if(pos > Sales.Count() - 1)
{
//Lets the user know the index out of bounds
MessageBox.Show("Index is out of bounds.");
return;
}
//Remove the product at the selected index
Sales.RemoveAt(pos);
}
}

Hangman game in C#

I was working on this hangman game in c# and so it's not working how I wanted.
The point of the game is next: When you start the game you need to open the .txt file where the words are written. When u load your .txt file with words game should show as many "" as how many letters your randomly chosen word from the .txt file has. When u click on the button with the letter game should check if the chosen word has that letter in it if it has one or more chosen letters, "" from the word should disappear and the chosen letter should show up, else our attempts should decrease for 1 and should show next picture in panel1.
I also want to set up the game so that only Cyrillic from the Serbian language can be used in the .txt file and the game itself.
Now about the problem, everything is working fine except the code where the game checks if a word has a chosen letter. Another problem is space, there should be the possibility of guessing multiple words at once but when I add space between two or more words game use "_" for space as well as for other characters, I need space to not be replaced with "__"
void NapraviLabels()
{
string cre = UzmiNasumicnuRijec();
string recc = cre.Replace(" ", "");
rec = recc.ToLower();
char[] chars = rec.ToCharArray();
int izmedju = 330 / chars.Length - 1;
for (int i = 0; i < chars.Length - 1; i++)
{
foreach(char c in rec)
{
if( c == ' ')
{
labels[i].Text = "";
}
else
{
labels.Add(new Label());
labels[i].Location = new Point((i * izmedju) + 10, 120);
labels[i].Text = "_";
labels[i].Parent = groupBox2;
labels[i].BringToFront();
labels[i].CreateControl();
}
}
}
}
string UzmiNasumicnuRijec()
{
string listaRijeci = File.ReadAllText(#filePath);
string[] rijeci = listaRijeci.Split('\n');
Random r = new Random();
return rijeci[r.Next(0, rijeci.Length -1)];
}
Button curButton = null;
Label curLabel = null;
private void slovo_Click(object sender, EventArgs e)
{
Button clickedbtn = (Button)sender;
Label lb = GetLBFromButton(clickedbtn);
if (curButton == null)
{
// first button clicked
curButton = clickedbtn;
curLabel = lb;
clickedbtn.Visible = false;
curLabel.Visible = true;
char slovo = curLabel.Text.ToLower().ToCharArray()[0];
if (rec.Contains(slovo))
{
char[] slova = rec.ToCharArray();
for (int i = 0; i < slova.Length; i++)
{
if (slova[i] == slovo)
labels[i].Text = slovo.ToString();
}
foreach (Label l in labels)
if (l.Text == "_") return;
MessageBox.Show("Победили сте!", "Честитамо");
Reset();
}
else
{
MessageBox.Show("Слово које сте унели се не налази у појму!");
NacrtajDijeloveTijela((DjeloviTijela)kolicina);
kolicina++;
if (kolicina == 9)
{
MessageBox.Show("Изгубили сте, појам је био: " + rec);
Reset();
}
}
curButton = null;
curLabel = null;
}
}
private void pogodirec_Click(object sender, EventArgs e)
{
if (textBox1.Text == rec)
{
MessageBox.Show("Победили сте!", "Честитамо");
Reset();
}
else
{
MessageBox.Show("Реч коју сте унели је погрешна!" , "Грешка!");
NacrtajDijeloveTijela((DjeloviTijela)kolicina);
kolicina++;
if (kolicina == 10)
{
MessageBox.Show("Изгубили сте, појам је био: " + rec);
Reset();
}
}
}

How do I get a value from a listbox instead of a textbox, my code is as follows

enter image description hereI'm trying to make a program that shows the prime numbers of the numbers added to the listbox from the textbox and then written in the listbox, with a message box, can anyone help me, where am I wrong?
private void button2_Click(object sender, EventArgs e)
int deneme = 0;
int sayilarim = Convert.ToInt32(textBox1.Text);
for (int i = 2; i < sayilarim; i++) {
if (sayilarim % i == 0)
deneme++;
}
if (deneme != 0){
listBox1.Items.Add(textBox1.Text + " Asal Sayi değildir.");
MessageBox.Show("Bu Bir Asal Sayi Değildir.");
} else {
listBox1.Items.Add(textBox1.Text + " sayidir.");
MessageBox.Show("Bu Bir Asal Sayi.");
}
textBox1.Clear();
}
MessageBox.Show(listBox1.Items.Count.ToString() + " Adet asal sayı var.");
First of all, your button2 is not getting value of Listbox1 ,
it takes value of textbox.
you have to take items of Listbox1 and put them in a list or etc.
and make your algorithm for them.
here is some sample code.
öncelikle buton 2 nin altında sayıları listbox içinden değil textbox'tan almışsın, onu düzeltmen gerek. listenin elemanlarında dönüp int bir listeye atama yapabilirsin. Bu adımları düzenledikten sonra altta verdiğim örnek kodu bir dene bakalım,
StringBuilder str = new StringBuilder();
str.AppendLine("Asal Olan Sayilar:");
List<int> lst = new List<int>(); // { 3, 4, 5, 10 };
for (int i = 0; i < ListBox1.Items.Count; i++)
{
lst.Add(Convert.ToInt32(ListBox1.Items[i].ToString()));
}
bool asalMi = true;
foreach (int value in lst)
{
asalMi = true;
for (int i = 2; i < value; i++)
{
if (value % i == 0)
{
asalMi = false;
}
}
if (asalMi)
str.AppendLine($"{value.ToString()} asaldir.");
}
MessageBox.Show(str.ToString);

How to display array elements, if the number of elements is a variable

I'm making a calculator in GUI, and I need some help.
When I enter some data in a text box, I need to store it in an array. This is how I thought of it.
int numOfPackages;//used to get user input
private void button3_Click(object sender, EventArgs e)
{
int[] weight = new int[numOfPackages];
for(int i = 0; i < numOfPackages; i++)
{
weight[i] = Convert.ToInt32(weightBox.Text);
}
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
}
And when I try to display the elements, it gives me the indexOutOfRange exception.
So, how do I display the elements of that array?
Thanks in advance.
This line
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
should be
foreach (int w in weight)
totalCostLabel.Text = "" + w;
Your current code iterates the array of weights, and tries to use the weight as an index into the array of weights, causing an index out of range exception.
Another problem is with the first loop: you are setting all values of weight to the same number:
weight[i] = Convert.ToInt32(weightBox.Text); // That's the same for all i-s
If weights are to be different, they should come from different weight boxes, or the string from a single weightBox should be processed in such a way as to produce multiple numbers (for example, by using string.Split).
You have multiple problems here. First is this:
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
This is iterating the weight array and using each value in that array. You then use that value as an index. Take the following example:
weight[0] = 0
weight[1] = 1
weight[2] = 15
In your code, the first two entries will work because there is an index of 0 and an index of 1. But when it gets to the last entry, it looks for an index of 15. You can fix this two ways, the first is to use a regular for loop:
for(int i=0; i < weight.Length; i++)
{
totalCostLabel.Text += weight[i];
}
This brings the second mistake. You aren't appending anything to your totalCostLabel in your code, you are just replacing the value. This will append all the values of weight together as one.
Another way to do this is to use the foreach loop:
foreach(int i in weight)
{
totalCostLabel.Text += i;
}
This is the same as above but you don't have to worry about indexing.
Bottom line, even after you fix your loop, you will probably need to fix the way that the label takes the text otherwise you won't get your desired result.
Maybe you wanted something more like?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
btnAdd.Enabled = false;
}
int[] weight;
int entriesMade;
int numOfPackages;
private void btnReset_Click(object sender, EventArgs e)
{
if (int.TryParse(numEntriesBox.Text, out numOfPackages))
{
weight = new int[numOfPackages];
entriesMade = 0;
btnReset.Enabled = false;
btnAdd.Enabled = true;
totalCostLabel.Text = "";
}
else
{
MessageBox.Show("Invalid Number of Entries");
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
int value;
if (int.TryParse(weightBox.Text, out value))
{
weight[entriesMade] = value;
weightBox.Clear();
totalCostLabel.Text = "";
int total = 0;
for (int i = 0; i <= entriesMade; i++)
{
total = total + weight[i];
if (i == 0)
{
totalCostLabel.Text = weight[i].ToString();
}
else
{
totalCostLabel.Text += " + " + weight[i].ToString();
}
}
totalCostLabel.Text += " = " + total.ToString();
entriesMade++;
if (entriesMade == numOfPackages)
{
btnAdd.Enabled = false;
btnReset.Enabled = true;
MessageBox.Show("Done!");
}
}
else
{
MessageBox.Show("Invalid Weight");
}
}
}

Numbered list on Richtextbox

I'm trying to add numbered list functionality to a text editor. RichTextbox already provides the SelectionBullet property to change a selection to a bulleted list. But i was unable to find a similar property to generate numbered list. Is there any standard way to create a numbered list on Richtextbox. If not, i would have to implement it myself so code snips that could help me do that will help, Thank you.
I know that a link is not gernerally accepted as a good answer, however the article RichTextBox with Search Line Numbering, Bulleting, Printing, Searching Support on CodeProject could probably help you out quite a bit with what you are looking for.
In this article, the author extends the RichTextBox control into something that can do what you are asking (and more), plus the code is posted there for all to see.
Well, i implemented it as follows.
private void btnNumbers_Click(object sender, EventArgs e)
{
string temptext = rtbMain.SelectedText;
int SelectionStart = rtbMain.SelectionStart;
int SelectionLength = rtbMain.SelectionLength;
rtbMain.SelectionStart = rtbMain.GetFirstCharIndexOfCurrentLine();
rtbMain.SelectionLength = 0;
rtbMain.SelectedText = "1. ";
int j = 2;
for( int i = SelectionStart; i < SelectionStart + SelectionLength; i++)
if (rtbMain.Text[i] == '\n')
{
rtbMain.SelectionStart = i + 1;
rtbMain.SelectionLength = 0;
rtbMain.SelectedText = j.ToString() + ". ";
j++;
SelectionLength += 3;
}
}
private void rtbMain_KeyDown(object sender, KeyEventArgs e)
{//this piece of code automatically increments the bulleted list when user //presses Enter key
int tempNum;
if (e.KeyCode == Keys.Enter)
try
{
if (char.IsDigit(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine()]))
{
if (char.IsDigit(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 1]) && rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 2] == '.')
tempNum = int.Parse(rtbMain.Text.Substring(rtbMain.GetFirstCharIndexOfCurrentLine(),2));
else tempNum = int.Parse(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine()].ToString());
if (rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 1] == '.' || (char.IsDigit(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 1]) && rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 2] == '.'))
{
tempNum++;
rtbMain.SelectedText = "\r\n" + tempNum.ToString() + ". ";
e.SuppressKeyPress = true;
}
}
}
catch{}
}
Here is my answer... which is easily readable and refineable. I took a much different approach but added the ability to remove the numbered list within the selection if it already exists. Please note that so far I have only lightly tested it and it seems to work good... but it may need further refinement.
private void btnOrdered_Click(object sender, EventArgs e)
{
string[] splitSelection = null;
// If selection split selection else split everything
if (this.txtCaptionEditor.SelectionLength > 0)
{
splitSelection = this.txtCaptionEditor.SelectedText.Replace("\r\n", "\n").Split("\n".ToCharArray());
}
else
{
splitSelection = this.txtCaptionEditor.Text.Replace("\r\n", "\n").Split("\n".ToCharArray());
}
bool Exists = false;
for (int i = 0; i < splitSelection.GetLength(0); i++)
{
// If Ordered List Allready exists in selection then remove else add
if (!string.IsNullOrEmpty(splitSelection[i]))
{
if (splitSelection[i].Substring(0, 2) == "1.") { Exists = true; }
}
}
for (int i = 0; i < splitSelection.GetLength(0); i++)
{
int lineCount = (i + 1);
if (Exists)
{
this.txtCaptionEditor.Text = this.txtCaptionEditor.Text.Replace(Convert.ToString(lineCount) + ". ", "");
}
else
{
if(!string.IsNullOrEmpty(splitSelection[i]))
{
this.txtCaptionEditor.Text = this.txtCaptionEditor.Text.Replace(splitSelection[i], Convert.ToString(lineCount) + ". " + splitSelection[i]);
}
}
}
}
private void txtCaptionEditor_KeyDown(object sender, KeyEventArgs e)
{
string[] splitSelection = this.txtCaptionEditor.Text.Replace("\r\n", "\n").Split("\n".ToCharArray());
if (e.KeyCode == Keys.Enter)
{
// Get Current Line Position
int currentLine = this.txtCaptionEditor.GetLineFromCharIndex(this.txtCaptionEditor.SelectionStart);
// Only Run if the previous line is greater than zero
if ((currentLine) >= 0)
{
// Loop through 100 possible numbers for match you can go higher
// If you think your numbered list could go above 100
for (int i = 0; i < 100; i++)
{
if (splitSelection[(currentLine)].Substring(0, 2) == Convert.ToString((i + 1)) + ".")
{
// If the substring of the current line equals a numbered list value.. enumerate next line
this.txtCaptionEditor.SelectedText = "\n" + (i + 2) + ". ";
e.SuppressKeyPress = true;
}
}
}
}
}

Categories

Resources