I'm trying to add variables from a text file into a datatable to be converted into a CSV file but I keep getting this error: "A column named 'Machine Number' already belongs to this DataTable" Im not sure what to do, any help would be appreciated, Thanks :)
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Globalization;
using System.Text;
namespace Ispy
{
public partial class Form1 : Form
{
private DataGridView dexRead;
DataColumn column;
DataTable Data = new DataTable("ISpy");
DataSet dataSet = new DataSet();
DataRow row;
public Form1()
{
InitializeComponent();
ReadFiles();
}
private void ReadFiles()
{
DataTable dataTable;
//Location of Dex Files
DirectoryInfo DexFiles = new DirectoryInfo(Properties.Settings.Default.Dex_File_Path);
//List of file names in Dex File folder
List<string> DexNames = new List<string>();
//Location of Input File
string ExcelFile = Properties.Settings.Default.Excel_File_Path;
//Read Input File
string[] ExcelLines = File.ReadAllLines(ExcelFile);
//Add names of each file to a list
foreach (FileInfo DexFile in DexFiles.GetFiles("*.dex"))
{
DexNames.Add(DexFile.Name);
}
//Excel Input and Dex File Data Marriage
foreach (string Line in ExcelLines)
{
row = Data.NewRow();
dataTable = new DataTable();
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "Machine Number";
column.ReadOnly = false;
column.Unique = true;
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Customer";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "MEI Total Vend Count";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "DEX Total Vend Count";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "Stock Sold";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "Capacity";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.DateTime");
column.ColumnName = "Next Scheduled Visit Date";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Scheduled Visit In:";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Scheduled Visit Day";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Next Visit Stock Prediction";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Route Number";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Route Driver Name";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Current Stock %";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.DateTime");
column.ColumnName = "Date/Time of DEX";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Telemetry Provider";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Days since last refill";
column.AutoIncrement = false;
Data.Columns.Add(column);
//column = new DataColumn();
//column.DataType = System.Type.GetType("System.String");
//column.ColumnName = "Machine #40% Stock in";
//column.AutoIncrement = false;
//Data.Columns.Add(column);
//column = new DataColumn();
//column.DataType = System.Type.GetType("System.String");
//column.ColumnName = "Machine #30% Stock in";
//column.AutoIncrement = false;
//Data.Columns.Add(column);
//column = new DataColumn();
//column.DataType = System.Type.GetType("System.String");
//column.ColumnName = "Optimal Fill Date";
//column.AutoIncrement = false;
//Data.Columns.Add(column);
//column = new DataColumn();
//column.DataType = System.Type.GetType("System.String");
//column.ColumnName = "Optimal Fill Date In:";
//column.AutoIncrement = false;
//Data.Columns.Add(column);
//column = new DataColumn();
//column.DataType = System.Type.GetType("System.String");
//column.ColumnName = "Optimal Fill Day";
//column.AutoIncrement = false;
//Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Sector";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Products";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Machine Type";
column.AutoIncrement = false;
Data.Columns.Add(column);
string[] LineInfo = Line.Split(',');
//Input File Variables (.Trim('"') is to remove artifacts leftover from Input File)
string MachineNumber = LineInfo[0].Trim('"');
string MachineLocation = LineInfo[1].Trim('"');
string TelemetryProvider = LineInfo[7].Trim('"');
string Capacity = LineInfo[9].Trim('"');
string MEIVendCount = LineInfo[10].Trim('"');
string MEICashCount = LineInfo[11].Trim('"');
string LastVisitDate = LineInfo[12].Trim('"');
string MachinePHYSID = LineInfo[13].Trim('"');
string NextScheduledVisit = LineInfo[14].Trim('"');
string RouteName = LineInfo[16].Trim('"');
string DriverName = LineInfo[17].Trim('"');
string MachineModel = LineInfo[18].Trim('"');
string MachineType = LineInfo[19].Trim('"');
string MachineSector = LineInfo[20].Trim('"');
string DEXVendCount = "";
string DEXCashCount = "";
string Difference = "";
string NextScheduledVisitDays = "";
string NextScheduledVisitDay = "";
string NextVisitStockPrediction = "";
string MachineStockSold = "";
string DexNameDate = "";
string DaysSinceLastFill = "";
string MachineStockAt30In = "";
string OptimalFillDate = "";
string OptimalFillDay = "";
//Read each Dex File and retrieve data
foreach (string DexName in DexNames)
{
string[] DexNameData = DexName.Split('_', '.');
int DexPHYSID = Int32.Parse(DexNameData[0]);
string dexNameDate = DexNameData[1] + DexNameData[2];
try
{
//Marriage of Excel File Data and Dex File Data
if (Int32.Parse(MachinePHYSID) == DexPHYSID)
{
//Dex File Variable's
string MeterLine = "";
//Calculate location of each Dex File
string DexFilePath = DexFiles.ToString() + DexName;
//Read all of the Dex File's lines and add to an array
string[] DexLines = File.ReadAllLines(DexFilePath);
//Find Meter Read line and add to an array
foreach (string DexLine in DexLines)
{
MeterLine = Array.Find(DexLines,
element => element.StartsWith("VA1", StringComparison.Ordinal));
}
//Split data from Meter Read line
if (MeterLine != null)
{
string[] MeterReads = MeterLine.Split('*');
//Assign Dex values to Dex variables
DEXCashCount = MeterReads[1];
DEXVendCount = MeterReads[2];
}
DateTime creationDate = DateTime.ParseExact(dexNameDate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
DateTime nextScheduledVisit = DateTime.ParseExact(NextScheduledVisit, "ddMMyy", CultureInfo.InvariantCulture);
TimeSpan scheduleDays = DateTime.Today - nextScheduledVisit;
TimeSpan LastVisitDays = DateTime.Today - DateTime.ParseExact(LastVisitDate, "ddMMyy", CultureInfo.InvariantCulture);
int Differential = Int32.Parse(DEXVendCount) - Int32.Parse(MEIVendCount);
int stockSold = Int32.Parse(Capacity) - Differential;
double percent = 0;
if (stockSold != 0)
{
percent = (double)(stockSold * 100) / Int32.Parse(Capacity);
}
else
{
percent = 0;
}
row["Machine Number"] = Int32.Parse(MachineNumber);
row["Customer"] = MachineLocation;
row["MEI Total Vend Count"] = Int32.Parse(MEIVendCount);
row["DEX Total Vend Count"] = Int32.Parse(DEXVendCount);
row["Stock Sold"] = Differential;
row["Capacity"] = Int32.Parse(Capacity);
row["Next Scheduled Visit Date"] = DateTime.ParseExact(NextScheduledVisit, "ddMMyy", CultureInfo.InvariantCulture);
row["Scheduled Visit In:"] = scheduleDays.Days.ToString() + " Days";
row["Scheduled Visit Day"] = nextScheduledVisit.DayOfWeek.ToString();
row["Next Visit Stock Prediction"] = "N/A";
row["Route Number"] = RouteName;
row["Route Driver Name"] = DriverName;
row["Current Stock %"] = percent.ToString() + " %";
row["Date/Time of DEX"] = creationDate;
row["Telemetry Provider"] = TelemetryProvider;
row["Days since last refill"] = LastVisitDays.Days.ToString() + " Days";
row["Sector"] = MachineSector;
row["Products"] = MachineModel;
row["Machine Type"] = MachineType;
dataTable.ImportRow(row);
}
}
catch(Exception e)
{
}
}
}
dataSet.Tables.Add(Data);
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = Data.Columns.Cast<DataColumn>().
Select(column1 => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row1 in Data.Rows)
{
IEnumerable<string> fields = row1.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(#"\\DC01\Dev\Dexr\Excel Files\Output\test.csv", sb.ToString());
}
private void Load_Properties()
{
string configFile = "config.cfg";
string path = Path.Combine(Environment.CurrentDirectory, #"Data\", configFile);
}
}
}
You need to declare datatable and add data columns only once outside foreach loop.
//Prepare Datatable and Add All Columns Here
dataTable = new DataTable();
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "Machine Number";
column.ReadOnly = false;
column.Unique = true;
column.AutoIncrement = false;
//Excel Input and Dex File Data Marriage
foreach (string Line in ExcelLines)
{
//Add new row and assign values to columns, no need to add columns again and again in loop which will throw exception
row = dataTable.NewRow();
//Map all the values in the columns
row["ColumnName"]= value;
//At the end just add that row in datatable
dataTable.Rows.Add(row );
}
i see you add columns to DataTable Data every time in foreach loop
so try adding these column outside the loop
private void sBAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("MonthlyActualPeriod1", typeof(System.Int32));
dt.Columns.Add("MonthlyActualPeriod2", typeof(System.Int32));
dt.Columns.Add("YearlyActualYear1", typeof(System.Int32));
dt.Columns.Add("YearlyActualYear2", typeof(System.Int32));
dt.Columns.Add("MonthlyBudgetPeriod1", typeof(System.Int32));
dt.Columns.Add("MonthlyBudgetPeriod2", typeof(System.Int32));
dt.Columns.Add("YearlyBudgetYear1", typeof(System.Int32));
dt.Columns.Add("YearlyBudgetYear2", typeof(System.Int32));
dt.Columns.Add("MonthlyActualCurrentPeriod", typeof(System.Int32));
dt.Columns.Add("YearlyActualCurrentyear", typeof(System.Int32));
dt.Columns.Add("YearlyActualPrioryear", typeof(System.Int32));
dt.Columns.Add("MonthlyBudgetCurrentPeriod", typeof(System.Int32));
dt.Columns.Add("YearlyBudgetCurrentyear", typeof(System.Int32));
dt.Columns.Add("YearlyBudgetPrioryear", typeof(System.Int32));
for (int i = 1; i < 61; i++)
{
dt.Columns.Add("MonthlyActualCurrentPeriod-" + i, typeof(System.Int32));
dt.Columns.Add("MonthlyBudgetCurrentPeriod-" + i, typeof(System.Int32));
}
int j = dt.Columns.Count;
DataRow row;
foreach (DataColumn cl in dt.Columns)
{
row = dt.NewRow();
for (int i = 0; i < j; i++)
{
row[i] = 1;
}
dt.Rows.Add(row);
}
this.gcCalcFields.DataSource = dt;
// Create an unbound column.
GridColumn unbColumn = gridView1.Columns.AddField("CalcFields");
unbColumn.VisibleIndex = gridView1.Columns.Count;
unbColumn.UnboundType = DevExpress.Data.UnboundColumnType.Object;
ColumnFilterMode prev = unbColumn.FilterMode;
unbColumn.FilterMode = ColumnFilterMode.Value;
gridView1.ShowUnboundExpressionEditor(unbColumn);
unbColumn.FilterMode = prev;
string Calculation = "";
Calculation = unbColumn.UnboundExpression;
LBCCalcFieldsActual.Items.Add(Calculation);
gridView1.Columns.Remove(gridView1.Columns["CalcFields"]);
}
I have this code to fill my datagridview from my database.
string query = "SELECT * From guestinfo";
using (con)
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, con))
{
using (DataTable dt = new DataTable())
{
adapter.Fill(dt);
dataGridView1.AutoGenerateColumns = false;
dataGridView1.ColumnCount = 4;
dataGridView1.Columns[0].Name = "RoomNumber";
dataGridView1.Columns[0].HeaderText = "Room Number";
dataGridView1.Columns[0].DataPropertyName= "RoomNumber";
dataGridView1.Columns[1].Name = "GuestName";
dataGridView1.Columns[1].HeaderText = "Guest Name";
dataGridView1.Columns[1].DataPropertyName = "GuestName";
dataGridView1.Columns[2].Name = "RoomType";
dataGridView1.Columns[2].HeaderText = "Room Type";
dataGridView1.Columns[2].DataPropertyName = "RoomType";
dataGridView1.Columns[3].Name = "Status";
dataGridView1.Columns[3].HeaderText = "Status";
dataGridView1.Columns[3].DataPropertyName = "Status";
dataGridView1.DataSource = dt;
dataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders);}}}
And this code to remove the rows with empty value.
for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--)
{
DataGridViewRow dataGridViewRow = dataGridView1.Rows[i];
foreach (DataGridViewCell cell in dataGridViewRow.Cells)
{
string val = cell.Value as string;
if (string.IsNullOrEmpty(val))
{
if (!dataGridViewRow.IsNewRow)
{
dataGridView1.Rows.Remove(dataGridViewRow);
break;
}
}
}
}
This Codes works but when I Add This code some runtime error happened.It Removes all my data. Even it is not empty.
dataGridView1.Columns[4].Name = "CheckDate";
dataGridView1.Columns[4].HeaderText = "Check Date";
dataGridView1.Columns[4].DataPropertyName = "CheckDate";
dataGridView1.Columns[5].Name = "OutDate";
dataGridView1.Columns[5].HeaderText = "Out Date";
dataGridView1.Columns[5].DataPropertyName = "OutDate";
I have a datagridview in c#. The datasource is a List. all the fileds are being added as columns, at the end I add another column: DataGridViewLinkColumn,
If i do a refresh/reload the DataGridViewLinkColumn is being added more then once.
Any help would be much appriciated.
private void bidListToGridT(List<Item> list)
{
dataGridView1.DataSource = null;
dataGridView1.DataSource = list;
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AllowUserToAddRows = false;
int i = 1;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Cells["NO"].Value = i;
i++;
}
dataGridView1.Columns[1].HeaderText = "Id";
dataGridView1.Columns[2].HeaderText = "Name";
DataGridViewLinkColumn Deletelink = new DataGridViewLinkColumn();
Deletelink.UseColumnTextForLinkValue = true;
Deletelink.HeaderText = "Delet";
Deletelink.DataPropertyName = "lnkColumn";
Deletelink.LinkBehavior = LinkBehavior.SystemDefault;
Deletelink.Text = "Delete";
dataGridView1.Columns.Add(Deletelink);
dataGridView1.Refresh();
}
To Avoid adding same column many times, Check whether such column existing in the gridview or not, Before adding them. For checking this you can use the following code.
bool hasDeleteColumn=false;
foreach (DataGridViewColumn item in dataGridView1.Columns)
{
if (item.GetType() == typeof(DataGridViewLinkColumn) && item.HeaderText=="Delete")
{
hasDeleteColumn = true;
break;
}
}
if(!hasDeleteColumn)
{
// Adding columns if not existing
DataGridViewLinkColumn Deletelink = new DataGridViewLinkColumn();
Deletelink.UseColumnTextForLinkValue = true;
Deletelink.HeaderText = "Delete";
Deletelink.DataPropertyName = "lnkColumn";
Deletelink.LinkBehavior = LinkBehavior.SystemDefault;
Deletelink.Text = "Delete";
dataGridView1.Columns.Add(Deletelink);
dataGridView1.Refresh();
}
I am grabbing eventlogs then displaying them in a datagrid, however for large logs it takes forever to return, so I would like to limit the logs by last 24hours but I am not sure how to do that. I would like to limit the collection prior to iterating through each entry because that would still take as long done that way. Any help would be totally appreciated!!!
namespace SysTools
{
public partial class LogViewer : Form
{
DataTable eventLog = new DataTable();
DataSet dataset1 = new DataSet();
private EventLog unhandledLogs;
public LogViewer(EventLog logs)
{
unhandledLogs = logs;
InitializeComponent();
}
private void LogViewer_Load(object sender, EventArgs e)
{
String currentLog = unhandledLogs.Log;
DataTable dataTable1 = new DataTable();
DataColumn column;
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Level";
dataTable1.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Category";
dataTable1.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.DateTime");
column.ColumnName = "DateTime";
dataTable1.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Message";
dataTable1.Columns.Add(column);
dataTable1.Rows.Clear();
DateTime systemtime = new DateTime();
Int32 count = unhandledLogs.Entries.Count;
for (int currLogIndex = 0; currLogIndex <= unhandledLogs.Entries.Count; currLogIndex++)
{
DataRow drnew = dataTable1.NewRow();
try
{
EventLogEntry currLogEntrys = unhandledLogs.Entries[currLogIndex];
EventLogEntry currLogEntry = currLogEntrys;
string entrytype = currLogEntrys.EntryType.ToString();
drnew["Level"] = entrytype;
drnew["Category"] = currLogEntry.Source;
drnew["DateTime"] = currLogEntry.TimeGenerated;
drnew["Message"] = currLogEntry.Message;
dataTable1.Rows.Add(drnew);
}
catch { }
}
dataGridView1.DataSource = dataTable1;
dataTable1.DefaultView.Sort = ("DateTime asc");
}
}
}
Have a look at the EventLogQuery and EventLogReader classes. In my example below, I'm reading the past 24 hours worth of logs from the Application Event Log, and putting them into a list. You can easily adapt to suit you own log and needs.
Note I'm doing something moderately hacky to get the date into the expected format (you should improve that), but see how I'm creating a query and then only processing the retrieved records.
public void GetEvents()
{
string FormattedDateTime = string.Format("{0}-{1}-{2}T{3}:{4}:{5}.000000000Z",
DateTime.Now.Year,
DateTime.Now.Month.ToString("D2"),
DateTime.Now.AddDays(-1).Day.ToString("D2"),
DateTime.Now.Hour.ToString("D2"),
DateTime.Now.Minute.ToString("D2"),
DateTime.Now.Second.ToString("D2"));
string LogSource = #"Application";
string Query = "*[System[TimeCreated[#SystemTime >= '" + FormattedDateTime + "']]]";
var QueryResult = new EventLogQuery(LogSource, PathType.LogName, Query);
var Reader = new System.Diagnostics.Eventing.Reader.EventLogReader(QueryResult);
List<EventRecord> Events = new List<EventRecord>();
bool Reading = true;
while (Reading)
{
EventRecord Rec = Reader.ReadEvent();
if (Rec == null)
Reading = false;
Events.Add(Rec);
// You could add to your own collection here instead of adding to a list
}
}
This question already has answers here:
Winforms DataGridView databind to complex type / nested property
(4 answers)
Closed 9 years ago.
I'm trying to populate a datagridview with the properties from a custom object that has a another custom object as a property.:
class InventoryItem
{
public NItem Item { get; set; }
public int Quantity { get; set; }
}
class NItem
{
public String ItemNumber { get; set; }
public String Title { get; set; }
public double WholesalePrice { get; set; }
public double RetailPrice { get; set; }
public String Model { get; set; }
public string URL { get; set; }
}
I want the datagridview to display each of the properties from NItem and the Quantity from Inventory Item. the code I'm using looks like this:
dataGridView1.DataSource = idr.GetAllItems();
idr reads the items from a database and returns a list of InventoryItems
Thanks in advance for any help.
EDIT:
I figured it out i used a data table and looped through the inventory producing unique columns. code:
// Create a new DataTable.
System.Data.DataTable table = new DataTable("InventoryTable");
// Declare variables for DataColumn and DataRow objects.
DataColumn column;
DataRow row;
// Create first column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ItemNumber";
column.AutoIncrement = false;
column.Caption = "Item Number";
column.ReadOnly = true;
column.Unique = true;
// Add the column to the table.
table.Columns.Add(column);
// Create second column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Title";
column.AutoIncrement = false;
column.Caption = "Title";
column.ReadOnly = true;
column.Unique = false;
// Add the column to the table.
table.Columns.Add(column);
// Create third column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Model";
column.AutoIncrement = false;
column.Caption = "Model";
column.ReadOnly = false;
column.Unique = false;
// Add the column to the table.
table.Columns.Add(column);
// Create fourth column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.Double");
column.ColumnName = "WholesalePrice";
column.AutoIncrement = false;
column.Caption = "Wholesale Price";
column.ReadOnly = false;
column.Unique = false;
// Add the column to the table.
table.Columns.Add(column);
// Create fifth column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.Double");
column.ColumnName = "RetailPrice";
column.AutoIncrement = false;
column.Caption = "Retail Price";
column.ReadOnly = false;
column.Unique = false;
// Add the column to the table.
table.Columns.Add(column);
// Create sixth column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "Quantity";
column.AutoIncrement = false;
column.Caption = "Quantity";
column.ReadOnly = false;
column.Unique = false;
// Add the column to the table.
table.Columns.Add(column);
// Create seventh column.
//column = new DataColumn();
//column.DataType = System.Type.GetType("System.DateTime");
//column.ColumnName = "DatePurchased";
//column.AutoIncrement = false;
//column.Caption = "Date Purchased";
//column.ReadOnly = false;
//column.Unique = false;
//// Add the column to the table.
//table.Columns.Add(column);
// Create eigth column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "URL";
column.AutoIncrement = false;
column.Caption = "URL";
column.ReadOnly = false;
column.Unique = false;
// Add the column to the table.
table.Columns.Add(column);
foreach (var item in items)
{
row = table.NewRow();
row["ItemNumber"] = item.Item.ItemNumber;
row["Title"] = item.Item.Title;
row["Model"] = item.Item.Model;
row["WholesalePrice"] = item.Item.WholesalePrice;
row["RetailPrice"] = item.Item.RetailPrice;
row["Quantity"] = item.Quantity;
row["URL"] = item.Item.URL;
table.Rows.Add(row);
}
You should try using databinding and viewmodels and a datagrid
Lets say that you have a view like that this in XAML
<UserControl
User Control properties
xmlns:vm="clr-namespace:ProjectName.ViewModel">
<UserControl.DataContext>
<view:ClassName/>
</Userontrol.DataContext>
<Grid>
<DataGrid ItemSource={"Binding InventoryItems"}/>
</Grid>
</UserControl>
Lets say you have an InventoryItem ViewModel
Public class InventoryItemViewModel: INotifyPropertyChanged
{
public InventoryItemsViewModel()
{
PopulateInventoryItems();
}
public List<InventoryItem> _inventoryItems;
private List<InventoryItem>
{
get
{
return _inventoryItems;
}
set
{
_inventoryItems = value;
RaiseProperyChanged();
}
}
//Populate your List here
Private PopulateInventoryItems()
{
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName] string PropertyName = null)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}