The name does not exist in the current context c# - c#

I'm trying to bind data with a chart to display it. However when I'm trying to link one of the columns with one of the axis of the chart it comes up with "The name Column1 does not exist in the current context" error. Does anybody know what I'm doing wrong and how to fix it?
Here is my code:
namespace bike
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var col1 = new List<string>();
var col2 = new List<string>();
var col3 = new List<string>();
var col4 = new List<string>();
var Column1 = col1.Select<string, int>(q => Convert.ToInt32(q));
var Column2 = col2.Select<string, int>(q => Convert.ToInt32(q));
var Column3 = col3.Select<string, int>(q => Convert.ToInt32(q));
var Column4 = col4.Select<string, int>(q => Convert.ToInt32(q));
dataGridView1.Columns.Add("col1", "Heart Rate");
dataGridView1.Columns.Add("col2", "Speed");
dataGridView1.Columns.Add("col3", "Power");
dataGridView1.Columns.Add("col4", "Altitude");
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
int row = 0;
string line;
bool isInHRData = false;
while ((line = sr.ReadLine()) !=null)
{
if (!isInHRData)
{
if (line != "[HRData]")
continue;
isInHRData = true;
continue;
}
else if (line.StartsWith("[") && line.EndsWith("["))
break;
string[] columns = line.Split('\t');
if (columns.Length > 0)
col1.Add(columns[0]);
if (columns.Length > 1)
col2.Add(columns[1]);
if (columns.Length > 2)
col3.Add(columns[2]);
if (columns.Length > 3)
col4.Add(columns[3]);
/*col1.Add(columns[0]);
col2.Add(columns[1]);
col3.Add(columns[2]);
col4.Add(columns[3]);
*/
dataGridView1.Rows.Add();
for (int i = 0; i < columns.Length; i++)
{
dataGridView1[i, row].Value = columns[i];
}
row++;
}
int maxSpeed = Column2.Max();
maxSpeed = maxSpeed / 10;
string MaxSpeed = Convert.ToString(maxSpeed);
textBox1.Text = MaxSpeed;
double aveSpeed = Column2.Average();
aveSpeed = aveSpeed / 10;
aveSpeed = Math.Round(aveSpeed, 0);
string AveSpeed = Convert.ToString(aveSpeed);
textBox2.Text = AveSpeed;
double aveHeart = Column1.Average();
aveHeart = Math.Round(aveHeart, 0);
string AveHeart = Convert.ToString(aveHeart);
textBox3.Text = AveHeart;
int maxHeart = Column1.Max();
string MaxHeart = Convert.ToString(maxHeart);
textBox4.Text = MaxHeart;
int minHeart = Column1.Min();
string MinHeart = Convert.ToString(minHeart);
textBox5.Text = MinHeart;
double avePower = Column3.Average();
avePower = Math.Round(avePower, 0);
string AvePower = Convert.ToString(avePower);
textBox6.Text = AvePower;
int maxPower = Column3.Max();
string MaxPower = Convert.ToString(maxPower);
textBox7.Text = MaxPower;
double aveAltitude = Column4.Average();
aveAltitude = Math.Round(aveAltitude, 0);
string AveAltitude = Convert.ToString(aveAltitude);
textBox8.Text = AveAltitude;
int maxAltitude = Column4.Max();
string MaxAltitude = Convert.ToString(maxAltitude);
textBox9.Text = MaxAltitude;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
chart1.DataSource = dataGridView1;
chart1.Series["Series1"].XValueMember = Column1;
chart1.Series["Series1"].YValueMembers = "test";
chart1.DataBind();
}
}
}

You're declaring Column1 as a local variable within your (rather long) button1_Click method. If you want it to be part of the state of the object, which will make it available in button2_Click, you should declare it as an instance variable instead.
You might want to consider what will happen if button 2 is clicked before button 1 though.

Related

C# Gembox Spreadsheet to populate comboBox

I am working on a program that uses comboboxes that are populated from a csv file, I initially just used streamreader to populate the combobox, but I was instructed to use gembox spreadsheet to populate it instead.
Here is the streamreader code that I used:
private static List<ItemLine> Readfile(string fileName, string defaultValueDescription)
{
string path = $".\\Backend Files\\{fileName}";
var items = new List<ItemLine>();
int row = 0;
//read the file
StreamReader reader = new StreamReader(path);
while (reader.EndOfStream == false)
{
string lines = reader.ReadLine();
row++;
if (row == 1)
{
items.Add(new ItemLine { Description = defaultValueDescription, Quantity = 0 });
continue;
}
string[] itemFields = lines.Split(",");
ItemLine IL = new ItemLine();
if (itemFields.Length == 2)
{
IL.Description = itemFields[0];
IL.Quantity = 0;
if (int.TryParse(itemFields[1], out int qty))
{
IL.Quantity = qty;
}
}
else if (itemFields.Length >= 3)
{
IL.Plan = itemFields[0];
IL.Description = itemFields[1];
IL.Quantity = 0;
if (int.TryParse(itemFields[2], out int qty))
{
IL.Quantity = qty;
}
}
///Add Items to List
items.Add(IL);
}
reader.Close();
return items;
}
Here is an example of what I used gembox spreadsheet for in another part of my program which I use to update the csv files with, I think the code I am trying to figure out would look something like:
public void updateFile(string filename, int range, ItemLine selectedItem, decimal outValue)
{
var fullPath = $".\\Backend Files\\{filename}";
SpreadsheetInfo.SetLicense("FREE -LIMITED-KEY");
var workbook = ExcelFile.Load(fullPath, new CsvLoadOptions(CsvType.CommaDelimited));
var worksheet = workbook.Worksheets[0];
for (int i = 1; i <= range; i++)
{
var plan = worksheet.Rows[i].Cells[0].Value;
var desc = worksheet.Rows[i].Cells[1].Value;
var csvDescription = plan + " - " + desc;
var platedescription = plan + " - ";
if (selectedItem.ComboDescription == csvDescription)
{
worksheet.Rows[i].Cells[2].Value = outValue;
}
if (selectedItem.plateDescription == platedescription)
{
worksheet.Rows[i].Cells[1].Value = outValue;
}
}
workbook.Save(fullPath, new CsvSaveOptions(CsvType.CommaDelimited));
}
Try this:
private static List<ItemLine> ReadFile(string fileName, string defaultValueDescription)
{
string path = $".\\Backend Files\\{filename}";
var workbook = ExcelFile.Load(path, new CsvLoadOptions(CsvType.CommaDelimited));
var worksheet = workbook.Worksheets[0];
var items = new List<ItemLine>();
items.Add(new ItemLine { Description = defaultValueDescription, Quantity = 0 });
foreach (var row in worksheet.Rows)
{
var cells = row.AllocatedCells;
var il = new ItemLine();
items.Add(il);
if (cells.Count == 2)
{
il.Description = cells[0].Value.ToString();
il.Quantity = cells[1].ValueType == CellValueType.Int ? cells[1].IntValue : 0;
}
else if (cells.Count >= 3)
{
il.Plan = cells[0].Value.ToString();
il.Description = cells[1].Value.ToString();
il.Quantity = cells[2].ValueType == CellValueType.Int ? cells[2].IntValue : 0;
}
}
return items;
}
Also, I'm not sure about the logic around the defaultValueDescription, it seems that in your StreamReader approach you just skip the first line in CSV because of it.
If that is the intended behavior, then add the .Skip(1) extension method from System.Linq, like this:
foreach (var row in worksheet.Rows.Skip(1))
{
// ...
}

How can I give separate events to buttons in datagridview?

dgvaciklamaBtn.Name = "Açıklama";
dgvaciklamaBtn.HeaderText = "Açıklama";
dgvkartvizitBtn.HeaderText = "Kartvizit";
dgvaciklamaBtn.Name = "Oku";
dgvaciklamaBtn.Text = "Oku";
dgvkartvizitBtn.Text = "Görüntüle";
dgvaciklamaBtn.UseColumnTextForButtonValue = true;
dgvkartvizitBtn.UseColumnTextForButtonValue = true;
dgvaciklamaBtn.DefaultCellStyle.BackColor = Color.Red;
dgvkartvizitBtn.DefaultCellStyle.BackColor = Color.Red;
dgvaciklamaBtn.DefaultCellStyle.SelectionBackColor = Color.White;
dgvkartvizitBtn.DefaultCellStyle.SelectionBackColor = Color.White;
dgvaciklamaBtn.Width = 70;
dgvkartvizitBtn.Width = 70;
firmalardtgview.DataSource = firmalartablo;
firmalardtgview.Columns[0].Width = 30;
firmalardtgview.Columns.Add(dgvaciklamaBtn);
firmalardtgview.Columns.Add(dgvkartvizitBtn);
firmalardtgview.Refresh();
private void firmalardtgview_CellContentClick(object sender, DataGridViewCellEventArgs e){
var senderGrid = (DataGridView)sender;
if (e.ColumnIndex == firmalardtgview.Columns["Açıklama"].Index)
{
string firmaid = firmalardtgview.CurrentRow.Cells["ID"].Value.ToString();
int index = firmaidler.IndexOf(firmaid);
MessageBox.Show(aciklamalar[index].ToString(), "Açıklama");
}
}
I want to make separate codes for read and explanation. Should I create separate events? Can it be solved with an if query? i am getting error like this
I solved the problem by taking the index number of the column and comparing it with the index number of the selected column.
It would be better if there is another shortcut. This is how it works.
string kartismi="";
if (e.ColumnIndex == 0)
{
string firmaid = firmalardtgview.CurrentRow.Cells["ID"].Value.ToString();
int index = firmaidler.IndexOf(firmaid);
MessageBox.Show(aciklamalar[index].ToString(), "Açıklama");
}
else if (e.ColumnIndex == 1)
{
string firmaid = firmalardtgview.CurrentRow.Cells["ID"].Value.ToString();
int index = firmaidler.IndexOf(firmaid);
SqlBaglanti.baglanti.Open();
SqlCommand kartvizitisimi = new SqlCommand("SELECT kartvizit_ismi FROM kartvizitler WHERE kartvizit_id=#kid", SqlBaglanti.baglanti);
kartvizitisimi.Parameters.AddWithValue("#kid", kartvizitIDler[index]);
SqlDataReader dr = kartvizitisimi.ExecuteReader();
if(dr.Read())
{
kartismi = dr["kartvizit_ismi"].ToString();
}
SqlBaglanti.baglanti.Close();
Process.Start(Path.Combine(Application.StartupPath,"Kartvizitler",kartismi));
}

How to store the value in datagridview in to a collection class C#

First, I import a csv file to the datagridview and changed it to the format that I want.
I'm able to filter out the data that i do not want by clicking a button, i get the data i want in the console by using console.writeline. (just for testing so i can see what's actually happen). There are quite numbers of column that do not content the data i want for calculation, so i use .contains() and .replace to filter it out.
Now, i want to store the cell.value.toString() which hold the value to an array but i have no idea how to implant array to it.
Here is the code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test2
{
public partial class Form1 : Form
{
OpenFileDialog openFile = new OpenFileDialog();
public int colC { get; private set; }
public Form1()
{
InitializeComponent();
}
public void Button1_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() == DialogResult.OK)
{
List<string[]> rows = File.ReadLines(openFile.FileName).Select(x => x.Split(',')).ToList();
DataTable dt = new DataTable();
List<string> headerNames = rows[0].ToList();
foreach (var headers in rows[0])
{
dt.Columns.Add(headers);
}
foreach (var x in rows.Skip(1).OrderBy(r => r.First()))
{
if (x[0] == "Lot ID") //linq to check if 2 lists are have the same elements (perfect for strings)
continue; //skip the row with repeated headers
if (x.All(val => string.IsNullOrWhiteSpace(val))) //if all columns of the row are whitespace / empty, skip this row
continue;
dt.Rows.Add(x);
}
dataGridView1.DataSource = dt;
dataGridView1.ReadOnly = true;
// dataGridView1.Columns["Lot ID"].ReadOnly = true;
//dataGridView1.Columns[" Magazine ID"].ReadOnly = true;
//dataGridView1.Columns["Frame ID"].ReadOnly = true;
}
}
public void Form1_Load_1(object sender, EventArgs e)
{
openFile.Filter = "CSV|*.csv";
}
public void Button2_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "txt files (*.txt)|*.txt|Csv files (*.csv)|*.csv";
sfd.FilterIndex = 2;
if (sfd.ShowDialog() == DialogResult.OK)
{
try
{
StreamWriter sw = new StreamWriter(sfd.FileName, false);
{
string columnHeaderText = "";
int countColumn = dataGridView1.ColumnCount - 1;
if (countColumn >= 0)
{
columnHeaderText = dataGridView1.Columns[0].HeaderText;
}
for (int i = 1; i <= countColumn; i++)
{
columnHeaderText = columnHeaderText + ',' + dataGridView1.Columns[i].HeaderText;
}
sw.WriteLine(columnHeaderText);
foreach (DataGridViewRow dataRowObject in dataGridView1.Rows)
{
if (!dataRowObject.IsNewRow)
{
string dataFromGrid = "";
dataFromGrid = dataRowObject.Cells[0].Value.ToString();
for (int i = 1; i <= countColumn; i++)
{
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
}
sw.WriteLine(dataFromGrid);
}
}
sw.Flush();
sw.Close();
}
}
catch (Exception exceptionObject)
{
MessageBox.Show(exceptionObject.ToString());
}
}
}
public void Button3_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
//prevent error occur coz , only execute the not null line
if(cell.Value != null)
{
string cellV = cell.Value.ToString();
//do operations with cell, filter out the unnecessary data
if (!cellV.Contains("="))
{
continue;
}
else if (cellV.Contains("P = "))
{
cellV = cellV.Replace("P = ", "");
}
else if (cellV.Contains("F = n/a"))
{
cellV =cellV.Replace("F = n/a", "0");
}
else if (cellV.Contains("F = "))
{
cellV = cellV.Replace("F = ", "");
}
Console.WriteLine(cellV + "\n");
}
}
}
}
}
}
Please have a look in the last method and the Picture.
Here is the output.
I skip all the data which is not related to calculation by using continue
How do i store the data that i filtered out in array???
Please do not hesitate to ask if you have any inquiry about the question.
I hope that this may help. First and more important, is that when you loop through a DataGridView that has a DataSource, it is better to do modifications/additions, etc… through the DataSource instead of the grid. In this example it will make no difference, however, the code below loops through the DataSource (the DataTable) and not the grid.
Below is a revised button 3 click that will convert the strings that contain equal “=” signs to decimal values. If the string that contains an equal “=” character and does not have a valid decimal number after the equal sign… zero (0) is returned. A helper method is used to take the string “P = XX.xx” and returns a valid decimal number or zero (0) if the number is invalid. Hope this makes sense.
private void button3_Click(object sender, EventArgs e) {
decimal decimalNumber = 0.0m;
foreach (DataRow row in dt.Rows) {
for (int i = 0; i < dt.Columns.Count; i++) {
if (row.ItemArray[i] != null) {
if (row.ItemArray[i].ToString().Contains("=")) {
decimalNumber = GetDecimalFromEquation(row.ItemArray[i].ToString());
textBox1.Text += decimalNumber.ToString() + Environment.NewLine;
}
}
}
textBox1.Text += Environment.NewLine;
}
}
private decimal GetDecimalFromEquation(string numberString) {
decimal parsedValue = 0.0m;
if (numberString.Contains("=")) {
numberString = numberString.Replace(" ", "");
string[] splitArray = numberString.Split('=');
if (splitArray.Length >= 2) {
decimal.TryParse(splitArray[1], out parsedValue);
}
}
return parsedValue;
}
Possible cleaner version of the read csv method.
private void button1_Click(object sender, EventArgs e) {
if (openFile.ShowDialog() == DialogResult.OK) {
List<string[]> rows = File.ReadLines(openFile.FileName).Select(x => x.Split(',')).ToList();
List<string> headerNames = rows[0].ToList();
foreach (var headers in rows[0]) {
dt.Columns.Add(headers);
}
foreach (var x in rows.Skip(1).OrderBy(r => r.First())) {
if ((!(x[0] == "Lot ID")) || (!(x.All(val => string.IsNullOrWhiteSpace(val)))))
dt.Rows.Add(x);
}
dataGridView1.DataSource = dt;
dataGridView1.ReadOnly = true;
}
}
Lastly, possible cleaner version of the write method. It uses the DataTable instead of the grid itself.
private void button2_Click(object sender, EventArgs e) {
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "txt files (*.txt)|*.txt|Csv files (*.csv)|*.csv";
sfd.FilterIndex = 2;
if (sfd.ShowDialog() == DialogResult.OK) {
try {
using (StreamWriter sw = new StreamWriter(sfd.FileName, false)) {
string columnString = "";
for (int i = 0; i < dt.Columns.Count - 1; i++) {
columnString += dt.Columns[i].ColumnName;
if (i < dataGridView1.Columns.Count - 2)
columnString += ",";
}
sw.WriteLine(columnString);
string rowString = "";
foreach (DataRow dr in dt.Rows) {
rowString = "";
for (int i = 0; i < dt.Columns.Count - 1; i++) {
rowString += dr.ItemArray[i].ToString();
if (i < dt.Columns.Count - 2)
rowString += ",";
}
sw.WriteLine(rowString);
}
}
}
catch (Exception exceptionObject) {
MessageBox.Show(exceptionObject.ToString());
}
}
}
You could use a List<string> values and store the values in the string using
values.Add(cellV);
You can then use values.ToArray() to get an array to the stored values.
Your function will look like this
public void Button3_Click(object sender, EventArgs e)
{
List<string> values = new List<string>();
// Create a new instance of the Form2 class
// Form2 goForm2 = new Form2();
// Show the settings form
// goForm2.Show();
//string checkP = "p = ";
// string removePE = checkP.Replace("P = ", "").Replace("F = ", "");
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
//prevent error occur coz , only execute the not null line
if(cell.Value != null)
{
string cellV = cell.Value.ToString();
//do operations with cell
if (!cellV.Contains("="))
{
continue;
}
else if (cellV.Contains("P = "))
{
cellV = cellV.Replace("P = ", "");
}
else if (cellV.Contains("F = n/a"))
{
cellV =cellV.Replace("F = n/a", "0");
}
else if (cellV.Contains("F = "))
{
cellV = cellV.Replace("F = ", "");
}
values.Add(cellV);
Console.WriteLine(cellV + "\n");
}
}
}
}

ASP.NET - Retrieving Grid View Data when EnableViewState is Set to False

I am building an application that needs to display data in a GridView control, grouped by a particular value, and then export it to PDF.I used this set of classes here (http://www.agrinei.com/gridviewhelper/gridviewhelper_pt.htm) for grouping, and it works well. However, I had to set EnableViewState to false for it to work properly. The problem comes when I need to export it to PDF. Previously (before using GridViewHelper), this was working. However, it now generates an empty report (I suppose because EnableViewState is false).
How can I save the data and structure of the GridView produced through use of the GridViewHelper class in order to export it to PDF?
Some of my aspx (portions of code omitted for brevity)
public partial class all : System.Web.UI.Page
{
Int32 userID;
Int32 currentID;
protected void Page_Load(object sender, EventArgs e)
{
GridViewHelper helper = new GridViewHelper(allTicketGrid);
helper.RegisterGroup("propName", true, true);
helper.ApplyGroupSort();
userID = Convert.ToInt32(Session["userID"]);
if (Session["userLevel"] == null || Session["userLevel"] == "")
{
Response.Redirect("~/Default.aspx");
}
if (!IsPostBack)
{
this.populate();
}
}
protected void populate()
{
toDateBox.Text = DateTime.Now.ToShortDateString();
fromDateBox.Text = DateTime.Now.ToShortDateString();
using (ticketModel dbContext = new ticketModel())
{
END_USER user = dbContext.END_USER.First(u => u.END_USER_ID == userID);
itemCheckBoxList.DataSource = dbContext.ITEM_TYPE.ToList();
itemCheckBoxList.DataTextField = "DESCRIPTION";
itemCheckBoxList.DataValueField = "ITEM_TYPE_ID";
itemCheckBoxList.DataBind();
List<Int32> propIDList = new List<Int32>();
foreach(END_USER_PROPERTY item in user.END_USER_PROPERTY.ToList() ) {
propIDList.Add((Int32)item.PROPERTY_ID);
}
locationCheckBoxList.DataSource = dbContext.PROPERTies.Where(p=> propIDList.Contains(p.PROPERTY_ID)).ToList();
locationCheckBoxList.DataTextField = "SHORT_NAME";
locationCheckBoxList.DataValueField = "PROPERTY_ID";
locationCheckBoxList.DataBind();
}
}
protected void exportReport(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < allTicketGrid.Columns.Count; i++)
{
dt.Columns.Add(allTicketGrid.Columns[i].HeaderText);
}
foreach (GridViewRow rowView in allTicketGrid.Rows)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < rowView.Cells.Count; i++)
{
dr[i] = rowView.Cells[i].Text.Trim();
}
dt.Rows.Add(dr);
}
Document doc = pdfWorker.readyDocument();
pdfWorker.createTable(doc, dt);
String filePath = Server.MapPath("~/reports/files/");
String fileName = "report_" + DateTime.Now.ToString("MM-dd-yyyy") + ".pdf";
filePath += fileName;
pdfWorker.savePDF(doc, filePath);
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(filePath);
Response.End();
}
protected void generateReport(object sender, EventArgs e)
{
int[] selectedLocations = getLocations();
int[] selectedItemTypes = getItems();
DateTime from = Convert.ToDateTime(fromDateBox.Text);
DateTime to = Convert.ToDateTime(toDateBox.Text);
if (!allButton.Checked)
{
Int32 statusID;
if (openButton.Checked)
{
statusID = 1;
}
else
{
statusID = 2;
}
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => t.STATUS_TYPE.STATUS_TYPE_ID == statusID && selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
else
{
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
}
and my pdfWorker class:
static class pdfWorker
{
public static Document readyDocument() {
Document doc = new Document();
Section section = doc.AddSection();
Style docStyles = doc.Styles["Normal"];
docStyles.Document.DefaultPageSetup.Orientation = MigraDoc.DocumentObjectModel.Orientation.Landscape;
docStyles.Font.Size = 8;
docStyles.ParagraphFormat.FirstLineIndent = 0;
return doc;
}
public static void createTable(Document document, DataTable dataTable)
{
Table table = new Table();
table.Format.Font.Size = 6;
table.BottomPadding = 10;
int colCount = dataTable.Columns.Count;
Row pdfRow;
Cell pdfCell;
for (int i = 0; i < colCount; i++)
{
table.AddColumn();
}
pdfRow = table.AddRow();
for (int i = 0; i < colCount; i++)
{
pdfCell = pdfRow.Cells[i];
pdfCell.Row.Format.Font.Size = 10;
pdfCell.AddParagraph(dataTable.Columns[i].ToString());
}
foreach (DataRow row in dataTable.Rows)
{
pdfRow = table.AddRow();
pdfRow.HeightRule = RowHeightRule.AtLeast;
for (int i = 0; i < colCount; i++)
{
pdfCell = pdfRow.Cells[i];
pdfCell.AddParagraph(row[i].ToString());
}
}
document.LastSection.Add(table);
}
public static void savePDF(Document doc, String fileName) {
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
SaveFileDialog saveDialog = new SaveFileDialog();
renderer.Document = doc;
renderer.RenderDocument();
renderer.PdfDocument.Save(fileName);
}
}
}
Thanks so much for any help.
You can put the code that populates the GridView in a separate method:
protected void generateReport(object sender, EventArgs e)
{
BindReportData();
}
private void BindReportData()
{
int[] selectedLocations = getLocations();
int[] selectedItemTypes = getItems();
DateTime from = Convert.ToDateTime(fromDateBox.Text);
DateTime to = Convert.ToDateTime(toDateBox.Text);
if (!allButton.Checked)
{
Int32 statusID;
if (openButton.Checked)
{
statusID = 1;
}
else
{
statusID = 2;
}
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => t.STATUS_TYPE.STATUS_TYPE_ID == statusID && selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
else
{
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
}
And call that method at the start of exportReport:
protected void exportReport(object sender, EventArgs e)
{
BindReportData();
...
}

how to create multiple column tree view with image

i have a problem. i am using the BrightIdeasSoftware.TreeListView to create treeview in my windows form and i also take the reference of How to create a MultiColumn treeview like this in C# Winforms app but i am not success to create this. Can you please tell me what i am doing mistake to create the treeview. The complete description is below.
i want to add the dynamic collapsible Panel and into this want to add tree in this.
The data will display into the panel according the collapsible panel header id .
i have a parent id and that can have multiple child.
Status Column will display one image
below is my code that i am using to create the treeview
class Node
{
public string Name { get; private set; }
public string Column1 { get; private set; }
public string Column2 { get; private set; }
public List<Node> Children { get; private set; }
public Node(string name, string col1, string col2)
{
this.Name = name;
this.Column1 = col1;
this.Column2 = col2;
this.Children = new List<Node>();
}
}
private void InitializeFristTabValue()
{
if (_UserDAC == null)
_UserDAC = new UserDAC();
try
{
DataTable dtUserGroup = _UserDAC.GetAllSECGROUPS(appDirectory, this.FindForm().Name, "InitializeFristTabValue()").Tables[0];
CommonDataGridBind cc = new CommonDataGridBind();
cc.GridviewGrouping(dtUserGroup, kryptonOutlookGridUserGroup, true, "GROUPID");
DataTable SEC_Info = _UserDAC.GetSECAPPINFO(appDirectory, this.FindForm().Name, "InitializeFristTabValue()").Tables[0];
int Location = 0;
foreach (DataRow dtrow in SEC_Info.Rows)
{
int APPID;
int.TryParse(dtrow["APPID"].ToString(), out APPID);
collapsiblePanelobj = new CollapsiblePanel();
if (Location == 0)
{
collapsiblePanelobj.Collapse = false;
//collapsiblePanelobj.Dock = System.Windows.Forms.DockStyle.Fill;
this.collapsiblePanelobj.Size = new System.Drawing.Size(1000, 150);
//DataTable SEC_InfoTreeView = _UserDAC.GetAPPITEMSbyAPPID(APPID, appDirectory, this.FindForm().Name, "InitializeFristTabValue()").Tables[0];
// ADDNode(APPID);
treeListView1.Dock = System.Windows.Forms.DockStyle.Fill;
//_panelBox.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left;
//_panelBox.Controls.Add(treeListView1);
//collapsiblePanelobj.Controls.Add(_panelBox);
collapsiblePanelobj.Controls.Add(treeListView1);
}
else
collapsiblePanelobj.Collapse = true;
Location = Location + 30;
collapsiblePanelobj.Name = dtrow["APPNAME"].ToString() + dtrow["APPID"].ToString();
collapsiblePanelobj.HeaderText = "PROGRAM: " + dtrow["APPNAME"].ToString();
collapsiblePanelobj.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
collapsiblePanelobj.BackColor = System.Drawing.Color.Transparent;
collapsiblePanelobj.HeaderCornersRadius = 5;
collapsiblePanelobj.HeaderFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold);
collapsiblePanelobj.HeaderImage = null;
collapsiblePanelobj.HeaderTextColor = System.Drawing.Color.Black;
collapsiblePanelobj.Location = new System.Drawing.Point(10, Location);
collapsiblePanelobj.RoundedCorners = true;
//this.collapsiblePanelobj.Dock = System.Windows.Forms.DockStyle.Fill;
this.collapsiblePanelobj.Size = new System.Drawing.Size(1000, 150);
collapsiblePanelobj.UseAnimation = true;
InitializeData(APPID);
FillTree();
AddTree();
panel1.Controls.Add(collapsiblePanelobj);
// GrpBoxUserGroupInfo.Controls.Add(collapsiblePanelobj);
}
}
catch (Exception ex)
{
LogsWrite(ex, appDirectory, this.FindForm().Name, "InitializeFristTabValue()");
}
}
public void ADDNode()
{
AddTree();
InitializeData();
FillTree();
}
private void AddTree()
{
treeListView1 = new BrightIdeasSoftware.TreeListView();
treeListView1.Dock = DockStyle.Fill;
this.Controls.Add(treeListView1);
}
private void InitializeData()
{
UserDAC _UserDAC = new UserDAC();
DataTable SEC_InfoTreeView = _UserDAC.GetAPPITEMSbyAPPID(2, "", this.FindForm().Name, "InitializeFristTabValue()").Tables[0];
data = new List<Node> {};
var parent1 = new Node("User Name ", "State ", "Static Caption ");
for (int i = 0; i < SEC_InfoTreeView.Rows.Count; i++)
{
int PrentID = Convert.ToInt32(SEC_InfoTreeView.Rows[i]["PARENTID"]);
if (PrentID == 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 0)
{
data.Add(parent1);
var parentAdd = new Node(Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]), "", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"]));
parent1 = parentAdd;
}
else if (PrentID != 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 2)
{
parent1.Children.Add(new Node(Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]), "", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"])));
}
}
}
private void FillTree()
{
// this.treeListView.SmallImageList = imageList1;
// set the delegate that the tree uses to know if a node is expandable
// treeListView1.Margin = new System.Windows.Forms.Padding(2, 1000, 2, 2);
treeListView1.CanExpandGetter = x => (x as Node).Children.Count > 0;
// set the delegate that the tree uses to know the children of a node
treeListView1.ChildrenGetter = x => (x as Node).Children;
// create the tree columns and set the delegates to print the desired object proerty
var nameCol = new BrightIdeasSoftware.OLVColumn("User Name", "Name");
nameCol.AspectGetter = x => (x as Node).Name;
nameCol.Width = treeListView1.Width / 3;
var col1 = new BrightIdeasSoftware.OLVColumn("State", "Column1");
col1.AspectGetter = x => (x as Node).Column1;
col1.Width = treeListView1.Width / 3;
var col2 = new BrightIdeasSoftware.OLVColumn("Static Caption", "Column2");
col2.AspectGetter = x => (x as Node).Column2;
col2.Width = treeListView1.Width / 3;
// add the columns to the tree
treeListView1.Columns.Add(nameCol);
treeListView1.Columns.Add(col1);
treeListView1.Columns.Add(col2);
// set the tree roots
this.treeListView1.Roots = data;
}
Thanks in advance for your help and comments

Categories