List of string to use in labels c# - c#

First. I create a group of 5 labels using a for
for (byte fila = 0; fila < 5; fila++)
{
Label letras = new Label();
letras.Height = alto;
letras.Width = ancho;
letras.BackColor = Color.Blue;
letras.ForeColor = Color.AntiqueWhite;
letras.Font = new Font("Arial", 60);
letras.TextAlign = ContentAlignment.MiddleCenter;
letras.BorderStyle = BorderStyle.FixedSingle;
letras.Left = 200 + (ancho + 20) * fila;
letras.Top = 60;
letras.Text = null;
letras.Visible = false;
letras.MouseMove += new
System.Windows.Forms.MouseEventHandler(this.letras_MouseMove);
this.Controls.Add(letras)
Second. I have a list of words declared as list of strings of 5 characters.
List <string> palabras = new List <string> { "limón", "bufón", "leche", "video",
"guiso",
"dulce", "gusto", "audaz", "vacío", "huevo", "avena", "guapo", "ozono",
"audio",
"zanja", "pausa", "freno", "débil", "hurto", "otoño", "libro", "pluma",
"disco",
"fruta", "melón", "papel", "mapeo", "nuevo", "banco", "tigre", "mundo",
"hueco",
"cable", "funda", "lápiz", "botón", "tonto", "regla", "tipas", "canal" };
I need to call one of them (words) and put each of the characters in a label of the group of labels I created first, in an altered order (5, 3, 1, 2, 4). I ´ve tried with substrings function but I always have errors. ¿Any suggestions?

string is basically an array of char, so you can access specific chars by their index, e.g.
string text = "Hello world!";
// this will write 'H'
Console.WriteLine(text[0]);

Related

How to add multiple texts on Visio connector shapes using the c#/vba code?

I want to add multiple texts on the connector line as per the image below. I am using c# code to automate the process. Below is my code which I have used. It is not giving the exact output as I had expected. Any help in this regard would be highly appreciated.
Visio.Shape vsoLastShape = visioPage.Shapes.get_ItemFromID(lastshapeID);
vsoLastShape.ConvertToGroup();
Visio.Selection vsoSelections = app.ActiveWindow.Selection;
vsoSelections.Select(vsoLastShape, (short)VisSelectArgs.visSelect);
Visio.Shape vsoGroupShape = vsoSelections.Group();
vsoGroupShape.Text = "Testing 12";
vsoGroupShape.TextStyle.PadLeft(10);
Whatever method (manual, C#, VBA or whatevber) you use, one shape can only contain one text. If you want to add more than one text then you need to convert the shape into a grouped shape. Then you can add a shape to the group and set that sub-shape's text to what you want.
Shape .Characters object used in conjunction with .Text allows for some flexibility.
private string nl = Environment.NewLine;
public void MultiText() {
try {
// using = System.Windows.Forms;
// using Vis = Microsoft.Office.Interop.Visio;
Vis.Application app = Globals.ThisAddIn.Application; // or launch Visio
Vis.Document vDoc = app.Documents.Add(""); // new blank document
Vis.Shape c1 = app.ActivePage.DrawOval(1, 1, 1.5, 1.5);
Vis.Shape s1 = app.ActivePage.DrawLine(1.5, 1.25, 4, 1.25);
s1.Text = $"Shape1{nl}Line2";
Vis.Shape c2 = app.ActivePage.DrawOval(4, 1, 4.5, 1.5);
Vis.Shape c3 = app.ActivePage.DrawOval(1, 3, 1.5, 3.5);
Vis.Shape s2 = app.ActivePage.DrawLine(1.5, 3.25, 4, 3.25);
s2.Text = $"Shape2";
Vis.Shape c4 = app.ActivePage.DrawOval(4, 3, 4.5, 3.5);
app.ActiveWindow.CenterViewOnShape(c4, Vis.VisCenterViewFlags.visCenterViewDefault);
app.ActiveWindow.Zoom = 1.2;
app.ActiveWindow.Selection.DeselectAll();
app.DoCmd((short)VisUICmds.visCmdDeselectAll);
System.Windows.Forms.MessageBox.Show($"2 Shapes with text.", "Continue...");
// reset the Text on Shape #2 and define 2 separate ranges
s2.Text = "";
// alocate a range
Characters range1 = s2.Characters;
range1.Begin = 0;
range1.End = 3;
range1.Text = "Name";
// alocate another
Characters range2 = s2.Characters;
range2.Begin = 4;
//range2.End = 7;
range2.Text = $"{Environment.NewLine}Type";
MessageBox.Show($"Now change Font Size", "Continue...");
// change font size or any of numerous properties
range1.CharProps[(short)Vis.VisCellIndices.visCharacterSize] = 16;
range2.CharProps[(short)Vis.VisCellIndices.visCharacterSize] = 8;
//range2.CharProps[(short)Vis.VisCellIndices.visCharacterStrikethru] = 1; // 1-true 0-false
MessageBox.Show($"Big Name!{nl}little Type.", "OK to continue");
} catch (Exception ex) {
ta.LogIt($"Err {ex.Message} Trace {ex.StackTrace}");
}
}
You may want to check this post and used the uploaded stencil. (Requires registration to see and download the attachment):
http://visguy.com/vgforum/index.php?topic=6318.msg25957#msg25957

Removing selected items from the listbox and from the list

I have an application written in C# that needs to be converted to Python, since I have recently switched to Linux. It's a simple GUI application to manage unknown words while learning a new language. Nevertheless, I need remove_item() function for which I also need find_word() function.
In C#, I would create two following methods:
void Remove()
{
Word word = new Word();
try { word = FindWord(listView1.SelectedItems[0].Text); }
catch { return; }
if (listView1.SelectedItems.Count > 0)
{
try
{
foreach (ListViewItem eachItem in listView1.SelectedItems)
{
words.RemoveAll(x => x.WordOrPhrase == eachItem.Text);
listView1.Items[listView1.Items.Count - 1].Selected = true;
listView1.Items.Remove(eachItem);
}
}
catch { }
ClearAll();
ReadOnlyON();
}
else
{
MessageBox.Show("You have not selected any words!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
ReadOnlyOFF();
WordCount();
Sync();
}
private Word FindWord(string word)
{
return words.Find(x => x.WordOrPhrase == word);
}
...but I'm still a newbie when it comes to Python, so any help would be appreciated. Here is what I have so far:
When it comes to the FindWord() method, it could be rewritten as following:
def FindWord(word):
for x in words:
if x.WordOrPhrase == word:
return x
or
def FindWord(word):
return next((x for x in words if x.WordOrPhrase == word), None)
or
def FindWord(word):
return next(filter(lambda x: x.WordOrPhrase == word, words), None)
...but I'm struggling to rewrite Remove() method. Here is one way:
def remove_item(self):
word = self.listBox.get(ACTIVE)
new_word_list = [] # initialize empty list
delete_idxs = []
for idx, item in enumerate(self.words):
if item.wordorphrase == word:
delete_idxs.append(idx)
else:
new_word_list.append(item)
self.words = new_word_list # overwrite the old word_list with the new one
for idx in reversed(delete_idxs):
self.listBox.delete(idx)
...what I would like most is converting my C# method to Python. Here is what I have so far:
def remove_item(self):
word = Word()
try:
word = find_word(self.listBox.curselection())
except:
return
if self.listBox.len(curselection()) > 0:
try:
for item in self.listBox.curselection():
self.words.remove(lambda x: x.wordorphrase == item.text)
# listView1.Items[listView1.Items.Count - 1].Selected = true;
self.listBox.remove(item)
except:
pass
self.clear_all()
else:
pass
# show messagebox
I don't know how to access:
listView1.SelectedItems[0].Text
listView1.SelectedItems.Count > 0
listView1.SelectedItems
listView1.Items[listView1.Items.Count - 1].Selected
Here is what I have done so far:
# Vocabulary.py
# GUI program to manage unknown words
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import xml.etree.ElementTree as ET
import os
class Word:
def __init__(self, wordorphrase, explanation, translation, example):
self.wordorphrase = wordorphrase
self.explanation = explanation
self.example = example
self.translation = translation
class Vocabulary(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.master = master
self.master.resizable(width = False, height = False)
self.master.title("Vocabulary")
self.create_widgets()
self.words = []
self.load_words()
def on_closing(self):
self.save_all()
if messagebox.askokcancel("Quit", "Do you want to quit?"):
self.master.destroy()
def create_widgets(self):
self.buttons_frame = Frame(self.master)
self.buttons_frame.grid(row = 10, sticky = W)
self.search_frame = Frame(self.master)
self.search_frame.grid(row = 1, sticky = W, columnspan = 2)
self.comboBox = ttk.Combobox(self.search_frame,
width = 3)
self.comboBox.grid(row = 0, column = 14, sticky = W)
self.comboBox['values'] = ( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' )
self.btn_Add = Button(self.buttons_frame,
text = 'Add',
command = self.add_item)
self.btn_Add.grid(row = 0, sticky = W)
self.btn_Remove = Button(self.buttons_frame,
text = 'Remove',
command = self.remove_item)
self.btn_Remove.grid(row = 0, column = 1, sticky = W)
self.btn_Edit = Button(self.buttons_frame,
text = 'Edit',
command = self.edit_item)
self.btn_Edit.grid(row = 0, column = 2, sticky = W)
self.btn_Save = Button(self.buttons_frame,
text = 'Save',
command = self.save_item)
self.btn_Save.grid(row = 0, column = 3, sticky = W)
self.btn_Refresh = Button(self.buttons_frame,
text = 'Refresh',
command = self.refresh_all)
self.btn_Refresh.grid(row = 0, column = 4, sticky = W)
self.lblSearch = Label(self.search_frame, text = 'SEARCH: ')
self.lblSearch.grid(row = 0, column = 5, sticky = W)
self.txt_Search = Text(self.search_frame,
height = 1,
width = 70)
self.txt_Search.grid(row = 0, column = 6, columnspan = 3, sticky = W)
self.lblWordsOrPhrases = Label(self.master, text = 'WORDS/PHRASES:')
self.lblWordsOrPhrases.grid(row = 2, column = 0)
self.lblWordOrPhrase = Label(self.master, text = 'Word or phrase:')
self.lblWordOrPhrase.grid(row = 2, column = 1, sticky = W)
self.listBox = Listbox(self.master,
selectmode='extended',
height = 34,
width = 38)
self.listBox.grid(row = 3, column = 0, rowspan = 7, sticky = W)
self.txt_WordOrPhrase = Text(self.master,
height = 1,
width = 40)
self.txt_WordOrPhrase.grid(row = 3, column = 1, sticky = N)
self.lblExplanation = Label(self.master, text = 'Explanation:')
self.lblExplanation.grid(row = 4, column = 1, sticky = W)
self.txt_Explanation = Text(self.master,
height = 10,
width = 40)
self.txt_Explanation.grid(row = 5, column = 1, sticky = N)
self.lblTranslation = Label(self.master, text = 'Translation:')
self.lblTranslation.grid(row = 6, column = 1, sticky = W)
self.txt_Translation = Text(self.master,
height = 10,
width = 40)
self.txt_Translation.grid(row = 7, column = 1, sticky = N)
self.lblExamples = Label(self.master, text = 'Example(s):')
self.lblExamples.grid(row = 8, column = 1, sticky = W)
self.txt_Example = Text(self.master,
height = 10,
width = 40)
self.txt_Example.grid(row = 9, column = 1, sticky = S)
def load_words(self):
self.listBox.delete(0, END)
self.words.clear()
path = os.path.expanduser('~/Desktop')
vocabulary = os.path.join(path, 'Vocabulary', 'Words.xml')
if not os.path.exists(vocabulary):
if not os.path.exists(os.path.dirname(vocabulary)):
os.mkdir(os.path.dirname(vocabulary))
doc = ET.Element('Words')
tree = ET.ElementTree(doc)
tree.write(vocabulary)
else:
tree = ET.ElementTree(file=vocabulary)
for node in tree.findall('WordOrPhrase'):
w = Word(node.find('Word').text, node.find('Explanation').text, node.find('Translation').text,
node.find('Examples').text)
self.words.append(w)
self.listBox.insert(END, w.wordorphrase)
def save_all(self):
path = os.path.expanduser('~/Desktop')
vocabulary = os.path.join(path, 'Vocabulary', 'Words.xml')
tree = ET.ElementTree(file=vocabulary)
for xNode in tree.getroot().findall('WordOrPhrase'):
tree.getroot().remove(xNode)
for w in self.words:
xTop = ET.Element('WordOrPhrase')
xWord = ET.Element('Word')
xExplanation = ET.Element('Explanation')
xTranslation = ET.Element('Translation')
xExamples = ET.Element('Examples')
xWord.text = w.wordorphrase
xExplanation.text = w.explanation
xTranslation.text = w.translation
xExamples.text = w.example
xTop.append(xWord)
xTop.append(xExplanation)
xTop.append(xTranslation)
xTop.append(xExamples)
tree.getroot().append(xTop)
tree.write(vocabulary)
def add_item(self):
w = Word(self.get_word(), self.get_explanation(), self.get_translation(), self.get_example())
self.words.append(w)
self.listBox.insert(END, w.wordorphrase)
self.clear_all()
self.save_all()
def remove_item(self):
word = Word()
try:
word = find_word(self.listBox.curselection())
except:
return
if self.listBox.len(curselection()) > 0:
try:
for item in self.listBox.curselection():
self.words.remove(lambda x: x.wordorphrase == item.text)
# listView1.Items[listView1.Items.Count - 1].Selected = true;
self.listBox.remove(item)
except:
pass
self.clear_all()
else:
pass
# show messagebox
def edit_item(self):
pass
def save_item(self):
pass
def clear_all(self):
self.txt_WordOrPhrase.delete('1.0', END)
self.txt_Explanation.delete('1.0', END)
self.txt_Translation.delete('1.0', END)
self.txt_Example.delete('1.0', END)
def refresh_all(self):
pass
def get_word(self):
return self.txt_WordOrPhrase.get('1.0', '1.0 lineend')
def get_explanation(self):
return self.txt_Explanation.get('1.0', '1.0 lineend')
def get_translation(self):
return self.txt_Translation.get('1.0', '1.0 lineend')
def get_example(self):
return self.txt_Example.get('1.0', '1.0 lineend')
def find_word(word):
for x in self.words:
if x.wordorphrase == word:
return x
def main():
root = Tk()
gui = Vocabulary(root)
root.protocol('WM_DELETE_WINDOW', gui.on_closing)
root.mainloop()
if __name__ == '__main__':
main()
For my listboxes, I generally have the mode set to EXTENDED so that users can select one or more items and remove all at once. I do so via the following method:
# Function with Tk.Listbox passed as arg
def remove_from(list_box):
# Tuple of currently selected items in arg
selected_items = list_box.curselection()
# Initialize a 'repositioning' variable
pos = 0
for item in selected_items:
# Set index of each item selected
idx = int(item) - pos
# Deletes only that index in the listbox
list_box.delete(idx, idx)
# Increments to account for shifts
pos += 1
For example, lets say in my listbox I had 4 items. I then select the first item and the third item. By calling list_box.curselection() I've received the following:
selected_items = (0, 2)
Where 0 is the first item's position in the listbox, and 2 is the third item's position. Then for each item in my tuple, I establish its index.
Walking through this, for the first item the following takes place:
idx = 0 - 0
list_box.delete(0, 0)
pos = 1
So now I have deleted the item at position 0 (e.g. the first item) and my listbox has shifted! So the second is now the first, third is the second and fourth is the third. However, my tuple has not changed as it was the positions in the listbox of the original selection. This is key. What happens next is:
idx = 2 - 1
list_box.delete(1, 1)
pos = 2
Since the listbox shifted, position 1 now corresponds to the item that was originally in the third position of the listbox. This can continue for n positions.
For self.words removal
You could try the following:
# Function with Tk.Listbox and self.words[] passed as args
def remove_from(list_box, list):
# Tuple of currently selected items in arg
selected_items = list_box.curselection()
# List of Words already constructed
word_list = list
# Initialize a 'repositioning' variable
pos = 0
for item in selected_items:
# Set index of each item selected
idx = int(item) - pos
# Deletes only that index in the listbox
list_box.delete(idx, idx)
# Gets the string value of the given index
word = list_box.get(idx, idx)
# Removes the word from the list
if any(word in x for x in word_list):
word_list.remove(word)
# Increments to account for shifts
pos += 1

Span Two Columns When Dynamically Adding Controls

I have an ASP.NET web application. This application renders out glossary type items, similar to the following:
This goes through all the letters in the alphabet for items. I am rendering this out and appending it directly to a Controls collection in a Server Control using the following:
List<char> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray().ToList();
foreach (char c in alpha)
{
Label lblAlphaCharacter = new Label();
lblAlphaCharacter.Font.Size = 24;
lblAlphaCharacter.Font.Bold = true;
lblAlphaCharacter.Text = c.ToString(CultureInfo.InvariantCulture);
Controls.Add(lblAlphaCharacter);
Controls.Add(new LiteralControl("<p>"));
FilterOnAlphaCharacter(this, Page, c);
Controls.Add(new LiteralControl("<p>"));
}
private static void FilterOnAlphaCharacter(Control control, Page page, char character)
{
foreach (List<Things> item in items)
{
string title = item.Title;
string description = item.Definition;
HyperLink link = new HyperLink();
link.Text = title;
control.Controls.Add(link);
Label lblDescription = new Label();
lblDescription.Text = string.Format(" - {0}", description);
control.Controls.Add(lblDescription);
}
}
}
I am trying to, depending on the content, equally split this, so that it looks like this:
This can have different amounts of items. So in reality, there could be 25 entries under "A", and perhaps 1 under "Z". The above is just an example, it goes through all letters A-Z. The expected result would be based on the amount of content, it would equally split between two columns. I have to do this server-side (I was thinking using Table or HtmlTable and related objects).
Howe would you implement a solution for splitting the content equally in a Table or the likes (sort of indifferent on approach).
try this:
//it shows the number of line that inserting during the process
private int _inserteditemCount;
//its number of items in each column
private int _itemsCount;
//line height use for determine paragraph line height
private const string Lineheight = "30px";
protected void Page_Load(object sender, EventArgs e)
{
_inserteditemCount = 0;
var alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
//you can do this query in data access layer
var listCountcount = new Thingsclass().GetThings().Count;
//Count of rows on dictionary + number of leters
_itemsCount = (listCountcount + alpha.Count()) / 2;
var leftdiv = new HtmlGenericControl("div");
var rightdiv = new HtmlGenericControl("div");
//you can change this styles
leftdiv.Style.Add("display", "inline-block");
leftdiv.Style.Add("width", "50%");
leftdiv.Style.Add("float", "Left");
rightdiv.Style.Add("display", "inline-block");
rightdiv.Style.Add("float", "right");
rightdiv.Style.Add("width", "50%");
foreach (var c in alpha)
{
var lblAlphaCharacter = new Label();
lblAlphaCharacter.Font.Size = 24;
lblAlphaCharacter.Font.Bold = true;
lblAlphaCharacter.Text = c.ToString(CultureInfo.InvariantCulture);
var control = _inserteditemCount <= _itemsCount ? leftdiv : rightdiv;
var paragraph = new HtmlGenericControl("p");
paragraph.Style.Add("line-height", Lineheight);
paragraph.Controls.Add(lblAlphaCharacter);
control.Controls.Add(paragraph);
FilterOnAlphaCharacter(leftdiv, rightdiv, c.ToString());
_inserteditemCount++;
}
Panel1.Controls.Add(leftdiv);
Panel1.Controls.Add(rightdiv);
}
private void FilterOnAlphaCharacter(Control leftctr, Control rightctr, string character)
{
//you can do this query in data access layer
var items = new Thingsclass().GetThings().Where(c => c.chara.ToLower().Equals(character.ToLower()));
foreach (var item in items)
{
var paragraph = new HtmlGenericControl("p");
paragraph.Style.Add("line-height", Lineheight);
var control = _inserteditemCount <= _itemsCount ? leftctr : rightctr;
var title = item.Title;
var description = item.Description;
var link = new HyperLink { Text = title };
paragraph.Controls.Add(link);
var lblDescription = new Label { Text = string.Format(" - {0}", description) };
paragraph.Controls.Add(lblDescription);
_inserteditemCount++;
control.Controls.Add(paragraph);
}
}

Bullet points in Word with c# Interop

I have the following code which is supposed to add a bulleted list to a word document that I'm generating automatically. From other answers I believe the code is correct, but the result doesn't produce any bullet points at all, it doesn't seem to apply the indent either.
Any Ideas?
Microsoft.Office.Interop.Word.Paragraph assets;
assets = doc.Content.Paragraphs.Add(Type.Missing);
// Some code to generate the text
foreach (String asset in assetsList)
{
assetText = assetText + asset + "\n";
}
assets.Range.ListFormat.ApplyBulletDefault(Type.Missing);
// Add it to the document
assets.Range.ParagraphFormat.LeftIndent = -1;
assets.Range.Text = assetText;
assets.Range.InsertParagraphAfter();
This happens because you're adding multiple paragraphs to the range after the range (it seems that setting the Text property is equivalent to InsertAfter). You want to InsertBefore the range so that the formatting you set gets applied.
Paragraph assets = doc.Content.Paragraphs.Add();
assets.Range.ListFormat.ApplyBulletDefault();
string[] bulletItems = new string[] { "One", "Two", "Three" };
for (int i = 0; i < bulletItems.Length; i++)
{
string bulletItem = bulletItems[i];
if (i < bulletItems.Length - 1)
bulletItem = bulletItem + "\n";
assets.Range.InsertBefore(bulletItem);
}
Notice that we add an End of Paragraph mark to all items except the last one. You will get an empty bullet if you add one to the last.
This is based on Tergiver's answer. The difference is it inserts the list items in the correct order after the initially created paragraph. For your own use make the starting range equal to the item you want to insert the list after.
Paragraph assets = doc.Content.Paragraphs.Add();
rng = assets.Range;
rng.InsertAfter("\n");
start = rng.End;
end = rng.End;
rng = _oDoc.Range(ref start, ref end);
object listType = 0;
rng.ListFormat.ApplyBulletDefault(ref listType);
string[] bulletItems = new string[] { "One", "Two", "Three" };
for (int i = 0; i < bulletItems.Length; i++)
{
string bulletItem = bulletItems[i];
if (i < RowCount - 1)
bulletItem = bulletItem + "\n";
rng.InsertAfter(bulletItem);
}
Please note I don't really understand what I'm doing with the range here. This solution was arrived at after considerable trial and error. I suspect it may have to do with the fact that I'm reusing the same range and Tergiver's solution is grabbing a new range each time the range is accessed. I particularly don't understand the following lines:
rng.InsertAfter("\n");
start = rng.End;
end = rng.End;
rng = _oDoc.Range(ref start, ref end);
Generally any alterations to the above code and the list gets intermingled with the previous element. If somebody could explain why this works, I'd be grateful.
You can try below code block if you want list-sublist relations:
static void Main(string[] args)
{
try
{
Application app = new Application();
Document doc = app.Documents.Add();
Range range = doc.Range(0, 0);
range.ListFormat.ApplyNumberDefault();
range.Text = "Birinci";
range.InsertParagraphAfter();
ListTemplate listTemplate = range.ListFormat.ListTemplate;
//range.InsertAfter("Birinci");
//range.InsertParagraphAfter();
//range.InsertAfter("İkinci");
//range.InsertParagraphAfter();
//range.InsertAfter("Üçüncü");
//range.InsertParagraphAfter();
Range subRange = doc.Range(range.StoryLength - 1);
subRange.ListFormat.ApplyBulletDefault();
subRange.ListFormat.ListIndent();
subRange.Text = "Alt Birinci";
subRange.InsertParagraphAfter();
ListTemplate sublistTemplate = subRange.ListFormat.ListTemplate;
Range subRange2 = doc.Range(subRange.StoryLength - 1);
subRange2.ListFormat.ApplyListTemplate(sublistTemplate);
subRange2.ListFormat.ListIndent();
subRange2.Text = "Alt İkinci";
subRange2.InsertParagraphAfter();
Range range2 = doc.Range(range.StoryLength - 1);
range2.ListFormat.ApplyListTemplateWithLevel(listTemplate,true);
WdContinue isContinue = range2.ListFormat.CanContinuePreviousList(listTemplate);
range2.Text = "İkinci";
range2.InsertParagraphAfter();
Range range3 = doc.Range(range2.StoryLength - 1);
range3.ListFormat.ApplyListTemplate(listTemplate);
range3.Text = "Üçüncü";
range3.InsertParagraphAfter();
string path = Environment.CurrentDirectory;
int totalExistDocx = Directory.GetFiles(path, "test*.docx").Count();
path = Path.Combine(path, string.Format("test{0}.docx", totalExistDocx + 1));
app.ActiveDocument.SaveAs2(path, WdSaveFormat.wdFormatXMLDocument);
doc.Close();
Process.Start(path);
}
catch (Exception exception)
{
throw;
}
}
Attention this point: If you don't know input length, you must not define the end of range value like this:
static void Main(string[] args)
{
try
{
Application app = new Application();
Document doc = app.Documents.Add();
Range range = doc.Range(0, 0);
range.ListFormat.ApplyNumberDefault();
range.Text = "Birinci";
range.InsertParagraphAfter();
ListTemplate listTemplate = range.ListFormat.ListTemplate;
//range.InsertAfter("Birinci");
//range.InsertParagraphAfter();
//range.InsertAfter("İkinci");
//range.InsertParagraphAfter();
//range.InsertAfter("Üçüncü");
//range.InsertParagraphAfter();
Range subRange = doc.Range(range.StoryLength - 1, range.StoryLength - 1);
subRange.ListFormat.ApplyBulletDefault();
subRange.ListFormat.ListIndent();
subRange.Text = "Alt Birinci";
subRange.InsertParagraphAfter();
ListTemplate sublistTemplate = subRange.ListFormat.ListTemplate;
Range subRange2 = doc.Range(subRange.StoryLength - 1, range.StoryLength - 1);
subRange2.ListFormat.ApplyListTemplate(sublistTemplate);
subRange2.ListFormat.ListIndent();
subRange2.Text = "Alt İkinci";
subRange2.InsertParagraphAfter();
Range range2 = doc.Range(range.StoryLength - 1, range.StoryLength - 1);
range2.ListFormat.ApplyListTemplateWithLevel(listTemplate,true);
WdContinue isContinue = range2.ListFormat.CanContinuePreviousList(listTemplate);
range2.Text = "İkinci";
range2.InsertParagraphAfter();
Range range3 = doc.Range(range2.StoryLength - 1, range.StoryLength - 1);
range3.ListFormat.ApplyListTemplate(listTemplate);
range3.Text = "Üçüncü";
range3.InsertParagraphAfter();
string path = Environment.CurrentDirectory;
int totalExistDocx = Directory.GetFiles(path, "test*.docx").Count();
path = Path.Combine(path, string.Format("test{0}.docx", totalExistDocx + 1));
app.ActiveDocument.SaveAs2(path, WdSaveFormat.wdFormatXMLDocument);
doc.Close();
Process.Start(path);
}
catch (Exception exception)
{
throw;
}
}
You just need to keep track of the start and end positions of the list and then apply the list format.
Application wordApp = new Application() {
Visible = true
};
Document doc = wordApp.Documents.Add();
Range range = doc.Content;
range.Text = "Hello world!";
range.InsertParagraphAfter();
range = doc.Paragraphs.Last.Range;
// start of list
int startOfList = range.Start;
// each \n character adds a new paragraph...
range.Text = "Item 1\nItem 2\nItem 3";
// ...or insert a new paragraph...
range.InsertParagraphAfter();
range = doc.Paragraphs.Last.Range;
range.Text = "Item 4\nItem 5";
// end of list
int endOfList = range.End;
// insert the next paragraph before applying the format, otherwise
// the format will be copied to the suceeding paragraphs.
range.InsertParagraphAfter();
// apply list format
Range listRange = doc.Range(startOfList, endOfList);
listRange.ListFormat.ApplyBulletDefault();
range = doc.Paragraphs.Last.Range;
range.Text = "Bye for now!";
range.InsertParagraphAfter();

Shuffle string array without duplicates

I am using the Knuth-Fisher-Yates algorithm to display a shuffled array of string items on a windows form. I do not get any duplicates, which is what I was trying to achieve, however, it only spits out 12 of the 13 elements of the array. How can I get it to display all 13 elements of the array? Here is my code:
private void FormBlue1_Load(object sender, EventArgs e)
{
// set the forms borderstyle
this.FormBorderStyle = FormBorderStyle.Fixed3D;
// create array of stationOneParts to display on form
string[] stationOneParts = new string[13];
stationOneParts[0] = "20-packing";
stationOneParts[1] = "5269-stempad";
stationOneParts[2] = "5112-freeze plug";
stationOneParts[3] = "2644-o'ring";
stationOneParts[4] = "5347-stem";
stationOneParts[5] = "4350-top packing";
stationOneParts[6] = "5084-3n1 body";
stationOneParts[7] = "4472-packing washer";
stationOneParts[8] = "3744-vr valve o'ring";
stationOneParts[9] = "2061-packing spring";
stationOneParts[10] = "2037-packing nut";
stationOneParts[11] = "2015-latch ring";
stationOneParts[12] = "stem assembly";
Random parts = new Random();
// loop through stationOneParts using a Swap method to shuffle
labelBlueOne.Text = "\n";
for (int i = stationOneParts.Length - 1; i > 0; i--)
{
int j = parts.Next(i + 1);
Swap(ref stationOneParts[i], ref stationOneParts[j]);
// display in a random order
labelBlueOne.Text += stationOneParts[i] + "\n";
}
}
private void Swap(ref string firstElement, ref string secondElement)
{
string temp = firstElement;
firstElement = secondElement;
secondElement = temp;
}
You don't access the first element.
for (int i = stationOneParts.Length - 1; i >= 0; i--).
As you are showing the texts using the loop that swaps the items, you will not show the last item, because it's never swapped by itself.
Just show the last item after the loop:
labelBlueOne.Text += stationOneParts[0] + "\n";
Alternatively, you can display all the items outside the loop that shuffles them:
for (int i = stationOneParts.Length - 1; i > 0; i--) {
Swap(ref stationOneParts[i], ref stationOneParts[parts.Next(i + 1)]);
}
labelBlueOne.Text = "\n" + String.Join("\n", stationOneParts);
Change your loop condition to i >= 0.
Simpliest approach :
Random rnd = new Random();
var stationOneParts = new List<string>{
"20-packing",
"5269-stempad",
"5112-freeze plug",
"2644-o'ring",
"5347-stem",
"4350-top packing",
"5084-3n1 body",
"4472-packing washer",
"3744-vr valve o'ring",
"2061-packing spring",
"2037-packing nut",
"2015-latch ring",
"stem assembly"}.OrderBy(s => rnd.Next());
labelBlueOne.Text = string.Join(Environment.NewLine, stationOneParts);
Since you mention C# 4.0, why not write is C#-ish?
using System.Linq;
// ...
var stationOneParts = new [] { "20-packing",
"5269-stempad",
"5112-freeze plug",
"2644-o'ring",
"5347-stem",
"4350-top packing",
"5084-3n1 body",
"4472-packing washer",
"3744-vr valve o'ring",
"2061-packing spring",
"2037-packing nut",
"2015-latch ring",
"stem assembly" };
Random rand = new Random();
stationOneParts = stationOneParts
.Distinct() // see subject: '... without duplicates'
.Select(i => new { i, key=rand.Next() })
.OrderBy(p => p.key)
.Select(p => p.i)
.ToArray();

Categories