How to create a timeline chart control thing? - c#

I am trying to create a timeline, and have been trying to use chart control. but it is not working out as i only need the X value and the chart series is like, only AddY or AddXY, there's no AddX/AddXX2.
I know there's like, questions like this before and stuff. There's this person that asked
How to create a timeline control?
like, 3 years ago but i'm not sure what exactly they are saying in the answers and comments..
My current code is:
DirectoryInfo dInfo = new DirectoryInfo(tbSelectFolder.Text);
FileInfo[] Files = dInfo.GetFiles("*.ts");
List<string> fileNames = new List<string>();
List<DateTime> fileDates = new List<DateTime>();
chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.White;
chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.White;
chart1.ChartAreas[0].AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Solid;
chart1.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dash;
chart1.ChartAreas[0].AxisX.LabelStyle.ForeColor = Color.White;
chart1.ChartAreas[0].AxisY.LabelStyle.ForeColor = Color.White;
chart1.ChartAreas[0].AxisX2.Enabled = AxisEnabled.True;
foreach (FileInfo file in Files)
{
string filename = Path.GetFileNameWithoutExtension(file.Name);
string[] fileNameSplit = filename.Split(' ');
fileNames.Add(fileNameSplit[0]);
DateTime date = DateTime.ParseExact(fileNameSplit[1], "yyMMdd",null);
fileDates.Add(date);
}
foreach (var value in fileNames)
{
foreach (var value1 in fileDates)
{
chart1.Series["US"].Points.AddXY(value1, value);
}
}
This basically gives me this
The timeline i'm trying to create is basically like a time table. So, is there a way to make it look something like this

Here is a possible solution:
// set up from clean slate:
chart1.ChartAreas.Clear();
chart1.Series.Clear();
ChartArea CA = chart1.ChartAreas.Add("CA");
Series S1 = chart1.Series.Add("S1");
S1.ChartType = SeriesChartType.Column; // whatever..
// a few restriction for my own files:
CA.AxisX.Maximum = new DateTime(2014, 12, 31).ToOADate();
DirectoryInfo dInfo = new DirectoryInfo("D:\\");
FileInfo[] Files = dInfo.GetFiles("f*.png");
// staying with the file info list!
//List<string> fileNames = new List<string>();
//List<DateTime> fileDates = new List<DateTime>();
chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.White;
chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.White;
chart1.ChartAreas[0].AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Solid;
chart1.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dash;
chart1.ChartAreas[0].AxisX.LabelStyle.ForeColor = Color.White;
chart1.ChartAreas[0].AxisY.LabelStyle.ForeColor = Color.White;
chart1.ChartAreas[0].AxisX2.Enabled = AxisEnabled.True;
S1.IsValueShownAsLabel = true;
S1.LabelFormat = "YYY.MM";
// restrict to 20 files max:
for (int i = 0; i < Math.Min(20, Files.Length); i++)
{
FileInfo FI = Files[i];
int p = chart1.Series[0].Points.AddXY(FI.CreationTime, 1);
S1.Points[p].Label = Path.GetFileNameWithoutExtension(FI.FullName);
}

I hope this fits your needs: unfortunately the axis-label aren't perfect, thats why you can remove them completely by uncommenting the first three line of code .
//Just pass your list of dates to this function
private void DrawTimeline(List<DateTime> dates)
{
//chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.Black;
//chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.White;
//chart1.ChartAreas[0].AxisX.LabelStyle.Enabled = false;
chart1.ChartAreas[0].AxisY.IsStartedFromZero = false;
//initialize a legend with some settings
chart1.Legends.Clear();
chart1.Legends.Add("Timespans");
chart1.Legends[0].LegendStyle = LegendStyle.Table;
chart1.Legends[0].Docking = Docking.Bottom;
chart1.Legends[0].Alignment = StringAlignment.Center;
chart1.Legends[0].Title = "Timespans";
chart1.Legends[0].BorderColor = Color.Black;
chart1.Series.Clear();
string seriesname;
//adding the bars with some settings
for (int i = 0; i < dates.Count-1; i++)
{
seriesname = Convert.ToString(dates[i].Date + " - " + dates[i + 1].Date);
chart1.Series.Add(seriesname);
chart1.Series[seriesname].ChartType = SeriesChartType.RangeBar;
chart1.Series[seriesname].YValuesPerPoint = 2;
chart1.Series[seriesname].Points.AddXY("Timeline", dates[i].Date, dates[i + 1].Date);
chart1.Series[seriesname]["DrawSideBySide"] = "false";
chart1.Series[seriesname].BorderColor = Color.Black;
chart1.Series[seriesname].ToolTip = seriesname;
}
}

Related

Remove white space between Chart Area and Legends

How to remove this large blank space between my chart area and the legends? See that I even tried different docking styles but the gap is still there.
Any ideas?
I import the data from a CSV file, generated by another application. Every column is a new data series but they are all added into the same chart and chartArea element.
// Load data from CSV into a DataTable
DataTable dataTable = ReadCsvFile(System.IO.Path.GetFileName("mqlWeekRace.txt"), false);
Chart chart1 = new Chart();
chart1.Height = 1000;
chart1.Width = 1500;
chart1.ChartAreas.Add("ChartArea1");
chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineWidth = 1;
chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Dot;
chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineWidth = 1;
chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dot;
chart1.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = false;
// chart1.ChartAreas["ChartArea1"].AxisY.IsStartedFromZero = false;
// Line colors
string[] myColors = new string[] { "Blue", "DarkOrange", "Firebrick", "DarkSeaGreen", "DarkViolet", "Sienna",
"DarkOrchid", "IndianRed", "ForestGreen", "Teal", "MidnightBlue", "DimGray" };
int colorIndex = 0;
foreach (DataColumn col in dataTable.Columns)
{
if (!col.ColumnName.StartsWith("Data") && col.ColumnName.Length > 1)
{
chart1.Series.Add(col.ColumnName.ToString());
chart1.Series[col.ColumnName].ChartArea = "ChartArea1";
chart1.Legends.Add(new Legend(col.ColumnName));
chart1.Legends[col.ColumnName].LegendStyle = LegendStyle.Column;
chart1.Legends[col.ColumnName].Docking = Docking.Top;
chart1.Legends[col.ColumnName].Font = new Font(FontFamily.GenericSansSerif, 15);
chart1.Series[col.ColumnName].ChartType = SeriesChartType.Line;
chart1.Series[col.ColumnName].XValueMember = "Data";
chart1.Series[col.ColumnName].YValueMembers = col.ColumnName.ToString();
chart1.Series[col.ColumnName].XValueType = ChartValueType.Date;
chart1.Series[col.ColumnName].BorderWidth = 3;
chart1.Series[col.ColumnName].Color = System.Drawing.Color.FromName(myColors[colorIndex]);
colorIndex++;
}
}
chart1.DataManipulator.IsStartFromFirst = true;
chart1.DataSource = dataTable;
chart1.DataBind();

Where is data updated in a DataGridView?

I am creating a tab page entirley programatically from a button press in the root page of a tabbed control. At present all the page initialisation takes place in the button click method. After all the instantiation, data capture from file and so on, I finally want to adjust the column widths in the data grid view, so that all the row data appears without having to have horizontal scroll bars. With the help of all your contributors I have managed to get it all working but the last step. Running at full speed it appears the DataGridView is accessed before the data load from the table is complete as it fails with an exception because the count derived from RegistersGrid.ColumnCount (local variable l) is zero. It all works fine if I step through the code. I am assuming that I need to put a Mutex of some form to wait for the transfer to complete, but I can't work out where that is taking place in order to reset the flag! If someone can point me in the right direction or if there is better more structured way to approach this I would deeply appreciate the help :-)
I have included all the code in the method just in case, I am afraid I date back a long way so if this looks like the awkward child of assembler,pascal and c with a little c# thrown in, my apologies....it's my age :-)
private void AddModuleButton_Click(object sender, EventArgs e)
{
string ModuleID = null;
string ModuleTypeFileNumber = null;
string ModuleType = null;
int TabID = 0;
openFileDialog1.Filter = "Text Files (.txt)|*.txt";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
string newline;
if ((newline = reader.ReadLine()) != null)
{
string[] values = newline.Split((char)9);
ModuleTypeFileNumber = values[1];
}
if ((newline = reader.ReadLine()) != null)
{
string[] values = newline.Split();
ModuleID = values[0];
ModuleType = values[1];
}
bool AbsorbLines = true;
while (AbsorbLines && ((newline = reader.ReadLine()) != null))
{
string[] values = newline.Split();
if (values[0] == "Readings") AbsorbLines = false;
}
string[] columnnames = { "Summary", "access", "register", "Module & Name", "Value", "unit", "type", "Res" };
string[] columntypes = { "System.Boolean", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.String", "System.String" };
int[] columnwidth = { 1,2,3,35,10,5,5,5 };
DataTable dt = new DataTable();
for(int i =0; i < columnnames.Length; i++)
{
DataColumn colString = new DataColumn(columnnames[i]);
colString.DataType = System.Type.GetType(columntypes[i]);
dt.Columns.Add(colString);
}
while (ImportTable("Controls", reader.ReadLine(), dt, "RO")) { } // Import the "readings" section
while (ImportTable("Status bits", reader.ReadLine(), dt, "RW")) { } // Import the "controls" section
reader.Close();
registerTables.Add(ModuleID, dt);
// create a new tab page
TabPage page = new TabPage(ModuleID);
InterbusRegisters.TabPages.Add(page);
//
// tabPage1
//
Button ResizeButton = new Button();
Button RemoveButton = new Button();
Label VersionLabel = new Label();
Label SerialNolabel = new Label();
TextBox VersionNoTB = new TextBox();
TextBox SerialNoTB = new TextBox();
DataGridView RegistersGrid = new DataGridView();
//
// Set the properties of the DataGrid.
//
RegistersGrid.AccessibleName = ModuleID + "Grid";
RegistersGrid.Location = new System.Drawing.Point(3,29);
RegistersGrid.Width = page.Width - 6;
RegistersGrid.Height = page.Height - 29;
RegistersGrid.Anchor = (AnchorStyles.Top | AnchorStyles.Left);
RegistersGrid.DataSource = dt;
RegistersGrid.Dock = (DockStyle)2;
//
// RemoveButtonRegistersGrid
//
RemoveButton.BackColor = System.Drawing.Color.Red;
RemoveButton.Location = new System.Drawing.Point(3, 4);
RemoveButton.Name = "RemoveButton";
RemoveButton.Size = new System.Drawing.Size(75, 25);
RemoveButton.TabIndex = 0;
RemoveButton.Text = "Remove";
RemoveButton.UseVisualStyleBackColor = false;
RemoveButton.Click += new System.EventHandler(this.RemoveButton_Click);
//
// ResizeButton
//
ResizeButton.BackColor = System.Drawing.Color.DarkOrange;
ResizeButton.Location = new System.Drawing.Point(81, 4);
ResizeButton.Name = "ResizeButton";
ResizeButton.Size = new System.Drawing.Size(75, 25);
ResizeButton.TabIndex = 6;
ResizeButton.Text = "Resize";
ResizeButton.UseVisualStyleBackColor = false;
ResizeButton.Click += new System.EventHandler(this.ResizeButton_Click);
//
// SerialNolabel
//
SerialNolabel.AutoSize = true;
SerialNolabel.Location = new System.Drawing.Point(159, 10);
SerialNolabel.Name = "SerialNolabel";
SerialNolabel.Size = new System.Drawing.Size(53, 13);
SerialNolabel.TabIndex = 4;
SerialNolabel.Text = "Serial No:";
//
// SerialNoTB
//
SerialNoTB.Location = new System.Drawing.Point(215, 7);
SerialNoTB.Name = "SerialNoTB";
SerialNoTB.Size = new System.Drawing.Size(100, 20);
SerialNoTB.TabIndex = 1;
//
// VersionLabel
//
VersionLabel.AutoSize = true;
VersionLabel.Location = new System.Drawing.Point(318, 10);
VersionLabel.Name = "VersionLabel";
VersionLabel.Size = new System.Drawing.Size(45, 13);
VersionLabel.TabIndex = 5;
VersionLabel.Text = "Version:";
//
// VersionTB
//
VersionNoTB.Location = new System.Drawing.Point(366, 7);
VersionNoTB.Name = "VersionTB";
VersionNoTB.Size = new System.Drawing.Size(100, 20);
VersionNoTB.TabIndex = 2;
page.Controls.Add(ResizeButton);
page.Controls.Add(RemoveButton);
page.Controls.Add(VersionLabel);
page.Controls.Add(VersionNoTB);
page.Controls.Add(SerialNolabel);
page.Controls.Add(SerialNoTB);
page.Controls.Add(RegistersGrid);
page.Location = new System.Drawing.Point(4, 22);
page.Size = new System.Drawing.Size(716, 554);
page.TabIndex = 1;
page.UseVisualStyleBackColor = true;
page.Update(); // the following code fails
int k = dt.Columns.Count;
int l = RegistersGrid.ColumnCount;
for (int j = 0; j <= RegistersGrid.ColumnCount - 1; j++)
RegistersGrid.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
RegistersGrid.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
//datagrid has calculated it's widths so we can store them
for (int i = 0; i <= RegistersGrid.ColumnCount - 1; i++)
{
int colw = RegistersGrid.Columns[i].Width; //store autosized widths
RegistersGrid.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; //remove autosizing
RegistersGrid.Columns[i].Width = colw; //set width to calculated by autosize
}
}
}

Why when adding links to datagridview it's adding only one row?

In this case there are 40 links. but when running the program i see it's adding only one row the last one.
public Form1()
{
InitializeComponent();
label2.Visible = false;
label3.Visible = false;
label4.Visible = false;
label7.Visible = false;
tbxMainDownloadPath.Text = Properties.Settings.Default.LastSelectedFolder;
if (tbxMainDownloadPath.Text != "")
downloadDirectory = tbxMainDownloadPath.Text;
tracker = new DownloadProgressTracker.DownloadProgress(50, TimeSpan.FromMilliseconds(500));
string[] countries = File.ReadAllLines(#"CountriesNames.txt");
string[] countriesCodes = File.ReadAllLines(#"CountriesCodes.txt");
foreach (string country in countries)
{
countryList.Add(country);
string countryPath = Path.Combine(downloadDirectory, country);
if (!Directory.Exists(countryPath))
Directory.CreateDirectory(countryPath);
}
foreach (string code in countriesCodes)
{
codesList.Add(code);
}
codeToFullNameMap = codesList
.Select((code, index) => index)
.ToDictionary(
keySelector: index => codesList[index],
elementSelector: index => countryList[index]);
lines = File.ReadAllLines(#"links.txt");
for (int i = 0; i < lines.Length; i++)
{
RichTextBoxExtensions.AppendText(true, richTextBox1, "Ready: ", Color.Red, 8.25f);
richTextBox1.AppendText(lines[i] + (i < lines.Length - 1 ? Environment.NewLine : String.Empty));
}
for (int i = 0; i < countriesCodes.Length; i++)
{
dataGridView1.Columns.Clear();
dataGridView1.ColumnCount = 2;
dataGridView1.Columns[0].Name = "Country";
dataGridView1.Columns[1].Name = "Code";
var countryName = codeToFullNameMap[countriesCodes[i]];
string[] row = new string[] { countryName, countriesCodes[i] };
dataGridView1.Rows.Add(row);
DataGridViewLinkColumn dgvLink = new DataGridViewLinkColumn();
dgvLink.UseColumnTextForLinkValue = true;
dgvLink.LinkBehavior = LinkBehavior.SystemDefault;
dgvLink.HeaderText = "Link Data";
dgvLink.Name = "SiteName";
dgvLink.LinkColor = Color.Blue;
dgvLink.TrackVisitedState = true;
dgvLink.Text = lines[i];
dgvLink.UseColumnTextForLinkValue = true;
dataGridView1.Columns.Add(dgvLink);
}
}
In countriesCodes there are 40 items.
The first problem is that it's adding only one country and it's link and it's the last one, it's not adding the rest.
Second problem is how can i make it to be moved to the right the ? I mean when running i'm using the mouse to drag the link column to the right to the datagridview end side on the right. How can i make to be already to the right end side ? Screenshot added after i dragged it to the right:
And third last problem how to remove the highlight from Country ? I don't want it to highlight anything. Now the highlight is automatic on the country when running the program.
Upodate
Solved all the problems i had:
for (int i = 0; i < countriesCodes.Length; i++)
{
dataGridView1.ColumnCount = 2;
dataGridView1.Columns[0].Name = "Country";
dataGridView1.Columns[1].Name = "Code";
var countryName = codeToFullNameMap[countriesCodes[i]];
string[] row = new string[] { countryName, countriesCodes[i] };
dataGridView1.Rows.Add(row);
DataGridViewLinkColumn dgvLink = new DataGridViewLinkColumn();
dgvLink.UseColumnTextForLinkValue = true;
dgvLink.LinkBehavior = LinkBehavior.SystemDefault;
dgvLink.HeaderText = "Link Data";
dgvLink.Name = "SiteName";
dgvLink.LinkColor = Color.Blue;
dgvLink.TrackVisitedState = true;
dgvLink.Text = lines[i];
dgvLink.UseColumnTextForLinkValue = true;
dataGridView1.Columns.Add(dgvLink);
}
this.dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.DefaultCellStyle.SelectionBackColor = dataGridView1.DefaultCellStyle.BackColor;
dataGridView1.DefaultCellStyle.SelectionForeColor = dataGridView1.DefaultCellStyle.ForeColor;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.BackgroundColor = System.Drawing.SystemColors.Control;
for (int i = 0; i < countriesCodes.Length; i++)
{
dataGridView1.Columns.Clear();
You are clearing your columns 40 times, so only the last iteration through the loop leaves anything to display. Do all of your dataGridView1.Columns setup before the for loop. The for loop should only be adding Rows.

C# creating pictureboxes for every item in a list

So far i have
var championNamelist = new List<string>(championName);
var first5Names = championNamelist.Take(5);
var skip5Names = championNamelist.Skip(5);
foreach (string name in first5Names)
{
string getPNG = "http://ddragon.leagueoflegends.com/cdn/6.11.1/img/champion/" + png + ".png";
}
In the championNamelist are all the names found from an XML.
How do i get all the pictures shown on my form ?
if want dynamically create picture box then try
PictureBox[] p = new PictureBox[10];
for (int i = 0; i < 10; i++)
{
p[i] = new PictureBox();
p[i].ImageLocation = "location";
p[i].Location = new Point(0,0);
p[i].Size = new Size(50, 50);
this.Controls.Add(p[i]);
}

Open XML MS Word Table Heading Row Height Text Direction Bottom to Top Left to Right

I am using Open XML SDK 2.5 to insert Tables in a Word Document. The issue I currently have is with the row height of my table heading. It works fine with normal text direction of Left to Right Top to Bottom LTTB. However as soon as I set the Text Direction to Bottom to Top Left to Right BTLR my heading rows do not adjust to fit the cell contents.
Code Below
void InsertTable(string[,] tableData, int numberOfRows, int numberOfColumns, string locationInDocument, string textDirectionHeadings)
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(_newDocument, true))
{
var docPart = myDoc.MainDocumentPart;
var doc = docPart.Document;
var table = new Table();
var tableBorderTop = new TopBorder();
var tableBorderBottom = new BottomBorder();
var tableBorderLeft = new LeftBorder();
var tableBorderRight = new RightBorder();
var tableBorderHorizontal = new InsideHorizontalBorder();
var tableBorderVertical = new InsideVerticalBorder();
var tableProperties = new TableProperties();
var borders = new TableBorders();
// Set Border Styles for Table
tableBorderTop.Val = BorderValues.Single;
tableBorderTop.Size = 6;
tableBorderBottom.Val = BorderValues.Single;
tableBorderBottom.Size = 6;
tableBorderLeft.Val = BorderValues.Single;
tableBorderLeft.Size = 6;
tableBorderRight.Val = BorderValues.Single;
tableBorderRight.Size = 6;
tableBorderHorizontal.Val = BorderValues.Single;
tableBorderHorizontal.Size = 6;
tableBorderVertical.Val = BorderValues.Single;
tableBorderVertical.Size = 6;
// Assign Border Styles to Table Borders
borders.TopBorder = tableBorderTop;
borders.BottomBorder = tableBorderBottom;
borders.LeftBorder = tableBorderLeft;
borders.RightBorder = tableBorderRight;
borders.InsideHorizontalBorder = tableBorderHorizontal;
borders.InsideVerticalBorder = tableBorderVertical;
// Append Border Styles to Table Properties
tableProperties.Append(borders);
// Assign Table Properties to Table
table.Append(tableProperties);
//Adds the Table Headings for each Column
var tableRowHeader = new TableRow();
tableRowHeader.Append(new TableRowHeight() { HeightType = HeightRuleValues.Auto });
for (int i = 0; i < numberOfColumns; i++)
{
var tableCellHeader = new TableCell();
//Assign Font Properties to Run
var runPropHeader = new RunProperties();
runPropHeader.Append(new Bold());
runPropHeader.Append(new Color() { Val = "000000" });
//Create New Run
var runHeader = new Run();
//Assign Font Properties to Run
runHeader.Append(runPropHeader);
var columnHeader = new Text();
//Assign the Pay Rule Name to the Run
columnHeader = new Text(tableData[0, i]);
runHeader.Append(columnHeader);
//Create Properties for Paragraph
var justificationHeader = new Justification();
justificationHeader.Val = JustificationValues.Left;
var paraPropsHeader = new ParagraphProperties(justificationHeader);
SpacingBetweenLines spacing = new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" };
paraPropsHeader.Append(spacing);
var paragraphHeader = new Paragraph();
paragraphHeader.Append(paraPropsHeader);
paragraphHeader.Append(runHeader);
tableCellHeader.Append(paragraphHeader);
var tableCellPropertiesHeader = new TableCellProperties();
var tableCellWidthHeader = new TableCellWidth();
tableCellPropertiesHeader.Append(new Shading() { Val = ShadingPatternValues.Clear, Color = "auto", Fill = "#C0C0C0" });
var textDirectionHeader = new TextDirection();
if (textDirectionHeadings == "BTLR")
{
textDirectionHeader.Val = TextDirectionValues.BottomToTopLeftToRight;
}
if (textDirectionHeadings == "LRTB")
{
textDirectionHeader.Val = TextDirectionValues.LefToRightTopToBottom;
}
tableCellPropertiesHeader.Append(textDirectionHeader);
tableCellWidthHeader.Type = TableWidthUnitValues.Auto;
tableCellPropertiesHeader.Append(tableCellWidthHeader);
tableCellHeader.Append(tableCellPropertiesHeader);
tableRowHeader.Append(tableCellHeader);
}
tableRowHeader.AppendChild(new TableHeader());
table.Append(tableRowHeader);
//Create New Row in Table for Each Record
int r = 1;
for (int a = 0; a < (numberOfRows - 1); a++)
{
var tableRow = new TableRow();
for (int i = 0; i < numberOfColumns; i++)
{
var propertyText = tableData[r, i];
var tableCell = new TableCell();
//Assign Font Properties to Run
var runProp = new RunProperties();
runProp.Append(new Bold());
runProp.Append(new Color() { Val = "000000" });
//Create New Run
var run = new Run();
//Assign Font Properties to Run
run.Append(runProp);
//Assign the text to the Run
var text = new Text(propertyText);
run.Append(text);
//Create Properties for Paragraph
var justification = new Justification();
justification.Val = JustificationValues.Left;
var paraProps = new ParagraphProperties(justification);
var paragraph = new Paragraph();
paragraph.Append(paraProps);
paragraph.Append(run);
tableCell.Append(paragraph);
var tableCellProperties = new TableCellProperties();
var tableCellWidth = new TableCellWidth();
tableCellWidth.Type = TableWidthUnitValues.Auto;
tableCellProperties.Append(tableCellWidth);
tableCell.Append(tableCellProperties);
tableRow.Append(tableCell);
}
r = r + 1;
table.Append(tableRow);
};
var res = from bm in docPart.Document.Body.Descendants<BookmarkStart>()
where bm.Name == locationInDocument
select bm;
var bookmark = res.SingleOrDefault();
var parent = bookmark.Parent; // bookmark's parent element
Paragraph newParagraph = new Paragraph();
parent.InsertAfterSelf(newParagraph);
if (bookmark != null)
{
newParagraph.InsertBeforeSelf(table);
}
}
}

Categories