WinForm DataGridView Multi-Line - c#

This is my DataGridView.
I'd like to make multiple lines.
From: 1abcdefghijklmno
To: 1abcdefghijklmno
pqrstuvwxyzabcde
fghijklmnopqrstu
vwxyz
What do I have to do ?
My codes:
private void Form1_Load(object sender, EventArgs e)
{
var myArray1 = new string[] { "1abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "2abc" };
var myArray2 = new string[] { "3abc", "4abc" };
var myArray = new string[][] { myArray1, myArray2 };
foreach( var x in myArray )
dataGridView1.Rows.Add(x);
}
and another code page..
DataGridView part
// dataGridView1
dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridView1.DefaultCellStyle = dataGridViewCellStyle3;
dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridView1.RowsDefaultCellStyle = dataGridViewCellStyle4;
this.dataGridView1.RowTemplate.DefaultCellStyle.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
I think I did all I can do.
Columns parts 1
// Column1
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.Column1.DefaultCellStyle = dataGridViewCellStyle1;
Columns parts 2
// Column2
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.Column2.DefaultCellStyle = dataGridViewCellStyle2;
Regards

These two lines should do the trick:
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
dataGridView1.RowsDefaultCellStyle.WrapMode = DataGridViewTriState.True;
But be aware, the the grid breaks new words to new lines and not single words. So if you write aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa you'll not get a wrap. But if you write aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaa you get a wrap.

Related

TextBox is not creating newline when reading text file C#

I have this program that supposed to reads multiple text files on the same folder, in that folder there's 2 text files which are supposed to be read, ok now I have to generate a new TextBox based on the total numbers of text files in that folder.
Main Goal
Load the contents of those files in each textbox
File1.txt contents will be loaded into TextBox1.
File2.txt contents will be loaded into TextBox2.
Content of File1.txt:
Title 1
ABCDEFG
Content of File2.txt:
Title 2
1234567890
The problem
Loading the contents of those files into each TextBoxes works fine, but the problem is that the newline isn't created on the TextBoxes.
Instead I got this on each textboxes:
TextBox 1:
Title 1ABCDEFG
TextBox 2:
Title 21234567890
Do the necessary stuff as soon the program loads:
private void Form1_Load(object sender, EventArgs e) {
flowLayoutPanel1.AutoScroll = true;
var dirs_notes = #"C:\MAIN_LOC\DATA_LOC\";
var count_notes = Directory.GetFiles(dirs_notes,"*.*",SearchOption.AllDirectories).Count();
string setup_path = #"C:\MAIN_LOC\DATA_LOC\";
if(Directory.Exists(setup_path)) {
string[] get_notes = Directory.GetFiles(dirs_notes, "*.txt", SearchOption.AllDirectories);
string[] get_texts = get_notes.Select(x => File.ReadAllText(x)).ToArray();
for(int i=0; i<count_notes; i++) {
int top = 25;
int h_p = 170;
var load_note = new Guna2TextBox() {
Text = "\n" + get_texts[i],
Name = "Note" + i,
Multiline = true,
AcceptsTab = true,
AcceptsReturn = true,
WordWrap = false,
Width = 230,
Height = 145,
BorderRadius = 8,
Font = new Font("Bahnschrift", 13),
ForeColor = Color.White,
FillColor = ColorTranslator.FromHtml("#1E1E1E"),
BorderColor = ColorTranslator.FromHtml("#2C2C2C"),
Location = new Point(450, top)
};
top += h_p;
flowLayoutPanel1.Controls.Add(load_note);
}
} else {
MessageBox.Show("There's problem with loading notes..", "Flow Notes System");
}
}
A fix could be using the Lines property instead of the Text property.
var dirs_notes = #"C:\MAIN_LOC\DATA_LOC\";
// Be sure to count only txt files here...
var count_notes = Directory.GetFiles(dirs_notes,"*.txt",SearchOption.AllDirectories).Count();
string setup_path = #"C:\MAIN_LOC\DATA_LOC\";
if(Directory.Exists(setup_path)) {
string[] get_notes = Directory.GetFiles(dirs_notes, "*.txt", SearchOption.AllDirectories);
var get_texts = get_notes.Select(x => File.ReadLines(x));
for(int i=0; i<count_notes; i++) {
....
var load_note = new Guna2TextBox() {
Lines = "\n" + get_texts[i].ToArray(),
But a better approach is to use this instead:
// No counting here (counting means load all
// files names in a memory array and the get its length
var files = Directory.EnumerateFiles(dirs_notes,"*.txt",SearchOption.AllDirectories)
int i = 1;
// Enumerate files one by one without loading all names in memory
foreach(string file in files) {
int top = 25;
int h_p = 170;
var load_note = new Guna2TextBox() {
// Set the textbox with the current file lines content
// again one by one without loading all texts in memory
Lines = File.ReadLines(file).ToArray(),
Name = "Note" + i,
...
}
i++;
.....
}

Replacing labels c# wpf

created a sports table that shows different statistics sorted by one property. When sorting for a different property I created completely new labels that just sit on top of the old ones instead of replacing them.
This is ran when a button is pressed:
private void Points_Order(object sender, RoutedEventArgs e)
{
List<Team> leagueTeams = new List<Team>();
using (StreamReader sr = new StreamReader("TXT1.txt"))
{
using (JsonReader jr = new JsonTextReader(sr))
{
JsonSerializer js = new JsonSerializer();
leagueTeams = js.Deserialize<List<Team>>(jr);
}
}
List<Team> sortedList = leagueTeams.OrderByDescending(o => o.points).ToList(); //orders the keagueTeams list by points and stores in a new list using linq
List<Label> TeamLabels = new List<Label>(); //makes list of labels that show the teams
List<string> Names = new List<string>(); //Creates a list for the names
List<Label> gamesPlayedLabels = new List<Label>();
List<int> GamesPlayed = new List<int>();
foreach (var properties in sortedList)
{
Names.Add(properties.name);//adds the name of each object into the Names list
GamesPlayed.Add(properties.gamesPlayed);
}
for (int i = 0; i < 20; i++)
{
string nameLab = Names[i];
TeamLabels.Add(new Label { Height = 100, Width = 100, Content = nameLab }); //sets position of the name labels
Canvas.SetLeft(TeamLabels[i], 0);
Canvas.SetTop(TeamLabels[i], (i * 19) + 19);
canvas1.Children.Add(TeamLabels[i]);
string played = Convert.ToString(GamesPlayed[i]);
gamesPlayedLabels.Add(new Label { Height = 100, Width = 100, Content = played });
Canvas.SetLeft(gamesPlayedLabels[i], 112);
Canvas.SetTop(gamesPlayedLabels[i], (i * 19) + 19);
canvas1.Children.Add(gamesPlayedLabels[i]);
}
}
When a second button is pressed the exact same code is ran but apart from
List<Team> sortedList = leagueTeams.OrderByDescending(o => o.points).ToList()
it is
List<Team> sortedList = leagueTeams.OrderBy(o => o.name).ToList();
so the question is can you replace existing labels so the table can be sorted?

iTextSharp - How can I iterate tables side by side in C# winforms?

I have a book library and I want to print library labels for them. When you select books from GridControl and click Print Labels button, the program creates labels on a pdf file like this:
private void btnQRPrintLabels_Click(object sender, EventArgs e)
{
// These are books' ids. Normally, these are retrieved from GridControl element.
var books_ids = new List<int>() {1, 2, 5, 6, 7, 12};
// I don't use PanelControl. But in the future, maybe I can use it later.
CreateLabels(books_ids, panelControl1);
}
And here is the contents of CreateLabels method:
public void CreateLabels(List<int> books_ids, PanelControl p)
{
var doc = new Document(PageSize.A4, 10, 10, 10, 10);
var m = new SaveFileDialog
{
Filter = #"PDF File Format|*.pdf",
FileName = "Labels.pdf"
};
if (m.ShowDialog() != DialogResult.OK) return;
var file = new FileStream(m.FileName, FileMode.Create);
wr = PdfWriter.GetInstance(doc, file);
doc.Open();
cb = wr.DirectContent;
wr.PageEvent = this;
// Labels are created from this method.
Labels(doc, books_ids);
doc.Close();
}
Finally, the contents of Labels method:
protected void Labels(Document doc, List<int> books_ids)
{
var i = 1;
foreach (var book_id in books_ids)
{
var alignment = (i % 2 != 0) ? Element.ALIGN_LEFT : Element.ALIGN_RIGHT;
// Book's informations are retrieved from Linq Connect Model.
var _connection = new LinqtoSQLiteDataContext();
var book = _connection.books.SingleOrDefault(b_no => b_no.id == book_id);
// Outer table to get rounded corner...
var table = new PdfPTable(1) { WidthPercentage = 48, HorizontalAlignment = alignment };
// Inner table: First cell for QR code and second cell for book's informations.
var inner_table = new PdfPTable(2) { WidthPercentage = 100 };
inner_table.DefaultCell.Border = Rectangle.NO_BORDER;
var inner_measurements = new[] { 40f, 60f };
inner_table.SetWidths(inner_measurements);
// Generate QR code in the `Tools` class, `GenerateQR` method.
System.Drawing.Image image = Tools.GenerateQR(100, 100, book?.isbn);
var pdfImage = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
var qr = iTextSharp.text.Image.GetInstance(pdfImage);
var a = new PdfPCell(qr) { Border = Rectangle.NO_BORDER };
var b = new PdfPCell(new Phrase(book?.name, font_normal)) { Border = Rectangle.NO_BORDER };
inner_table.AddCell(a);
inner_table.AddCell(b);
var s = new PdfPCell(inner_table)
{
CellEvent = new RoundRectangle(),
Border = Rectangle.NO_BORDER,
Padding = 2,
HorizontalAlignment = Element.ALIGN_LEFT
};
table.AddCell(s);
doc.Add(table);
i++;
}
}
These codes bring me labels like this:
But I want to get labels like this:
Because if I manage getting labels side by side, I print it to computer labels easily. Here is the computer label that I want to print to on it:
How can I iterate tables side by side?
Use one outer Table with
new PdfPTable(2) { WidthPercentage = 100 }
Then add all your inner tables to this one and at last add the outer table to the document. This way there is NO need to use that toggeling left/right alignment.
:edit:
var table = new PdfPTable(2) { WidthPercentage = 100 };
foreach (var book_id in books_ids)
{
// Book's informations are retrieved from Linq Connect Model.
var _connection = new LinqtoSQLiteDataContext();
var book = _connection.books.SingleOrDefault(b_no => b_no.id == book_id);
// Outer table to get rounded corner...
// Inner table: First cell for QR code and second cell for book's informations.
var inner_table = new PdfPTable(2) { WidthPercentage = 100 };
inner_table.DefaultCell.Border = Rectangle.NO_BORDER;
var inner_measurements = new[] { 40f, 60f };
inner_table.SetWidths(inner_measurements);
// Generate QR code in the `Tools` class, `GenerateQR` method.
System.Drawing.Image image = Tools.GenerateQR(100, 100, book?.isbn);
var pdfImage = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
var qr = iTextSharp.text.Image.GetInstance(pdfImage);
var a = new PdfPCell(qr) { Border = Rectangle.NO_BORDER };
var b = new PdfPCell(new Phrase(book?.name, font_normal)) { Border = Rectangle.NO_BORDER };
inner_table.AddCell(a);
inner_table.AddCell(b);
PdfPCell labelCell = new PdfPCell(inner_table)
{
CellEvent = new RoundRectangle(),
Border = Rectangle.NO_BORDER,
Padding = 2,
HorizontalAlignment = Element.ALIGN_LEFT
};
table.AddCell(labelCell);
}
doc.Add(table);
Just add page-level table (2 columns, 6 rows) and place each label into individual cell in this page-level table.

Select and merge a range of cells

I am trying to select the range A1 to C3 to affect a value but this code is not working:
worksheet.Select["A1:C3"].Value = "toto";
I am able to affect the value to each of the cell with this code (but that's not what I want):
worksheet.Cells["A1:C3"].Value = "toto";
I want to merge all cells from A1 to C3, and that this new cell contains toto value;
You first have to merge the cells like this:
worksheet.Cells["A1:C3"].Merge = true;
then to set the value you would either do this:
worksheet.Cells["A1:C3"].Value = "toto";
or set A1 to the value (since it's merged)
worksheet.Cells["A1"].Value = "toto";
Kelsey's method is more diect but if you want to use the Select methods for some reason:
[TestMethod]
public void MergeCellTest()
{
var existingFile = new FileInfo(#"c:\temp\temp.xlsx");
if (existingFile.Exists)
existingFile.Delete();
using (var package = new ExcelPackage(existingFile))
{
var workbook = package.Workbook;
var worksheet = workbook.Worksheets.Add("newsheet");
worksheet.Select("A1:C3");
worksheet.SelectedRange.Merge = true;
worksheet.SelectedRange.Value = "toto";
package.Save();
}
}

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);
}
}

Categories