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"]);
}
Related
I'm going to need help with this one. Been 2 days now without figuring out the root case.
In my application I add a set number of rows to a DataTable and display it through a DataGrid.
A timer is set to do some work on a interval (currently set to 10 seconds):
Iterate row by row on the DataTable.
Get the hostname from the column "hostname"
Ping the computer
If pingresult == success continue the operation and send a Windows Toast Message.
Adding the list of the computers to the DataTable and displaying them into DataGrid works fine.
The problem occurs after I hit the Start button which triggers the timer. The amount of time it takes before the error occurs depends on how many rows are added to the DataTable.
Sorry for all the info posted below here. The frustration has kicked in for me. Hopefully someone can spot the obvious and help me get passed this problem. I have commented out some of the code to narrow the where the problem is located.
For testing purposes the intital DataTable is created and DataGrid is populated with an empty table when I click the Test button.
void FillDataGrid()
{
try
{
ds.ReadXml(#"C:\Temp\ToastData.ds");
gridToastItems.ItemsSource = ds.Tables[0].DefaultView;
}
catch (Exception ioException)
{
dt.Clear();
DataColumn column;
//ID Column
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
column.ReadOnly = true;
column.Unique = true;
column.AutoIncrement = true;
dt.Columns.Add(column);
//// Make the ID column the primary key column.
//DataColumn[] PrimaryKeyColumns = new DataColumn[1];
//PrimaryKeyColumns[0] = dt.Columns["id"];
//dt.PrimaryKey = PrimaryKeyColumns;
// Hostname column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "hostname";
column.Caption = "Hostname";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
// Online column
column = new DataColumn();
column.DataType = System.Type.GetType("System.Boolean");
column.ColumnName = "online";
column.Caption = "Online";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
// OS Version column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "osversion";
column.Caption = "OS Version";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
// Lockscreen status column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "lockscreen";
column.Caption = "Lockscreen Status";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
// Toast type column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "toasttype";
column.Caption = "Toast Type";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
// Schedule column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "schedule";
column.Caption = "Schedule";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
// Result column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "status";
column.Caption = "Status";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
ds.Tables.Add(dt);
gridToastItems.ItemsSource = dt.DefaultView;
//DataColumn hostname = new DataColumn("Hostname", typeof(string));
//DataColumn online = new DataColumn("Online", typeof(bool));
//DataColumn osversion = new DataColumn("OS Version", typeof(string));
//DataColumn lockscreen = new DataColumn("Lockscreen Status", typeof(string));
//DataColumn toastname = new DataColumn("Toast Type", typeof(string));
//DataColumn schedule = new DataColumn("Schedule", typeof(string));
//DataColumn result = new DataColumn("Result", typeof(string));
//dt.Columns.Add(hostname);
//dt.Columns.Add(online);
//dt.Columns.Add(osversion);
//dt.Columns.Add(lockscreen);
//dt.Columns.Add(toastname);
//dt.Columns.Add(schedule);
//dt.Columns.Add(result);
//dt.AcceptChanges();
//gridToastItems.ItemsSource = dt.DefaultView;
//ds.Tables.Add(dt);
//ds.AcceptChanges();
}
}
The computers are added to the DataTable from a second form:
private void AddToastEntries()
{
bool exceptionCaught = false;
try
{
int lineCount = txtComputerNames.LineCount; //iterator for number of computernames in the textbox
if (lineCount > 1)
{
for (int i = 0; i < lineCount; i++)
{
string currentLine = txtComputerNames.GetLineText(i).ReplaceLineEndings("");
//Adding a new toast entry for each computername listed in the textbox
if (currentLine != "")
{
DataRow firstRow = MainWindow.ds.Tables[0].NewRow();
firstRow["hostname"] = currentLine;
firstRow["online"] = false;
firstRow["osversion"] = "";
firstRow["lockscreen"] = "";
firstRow["toasttype"] = "Windows Update";
firstRow["schedule"] = SelectedDateTime();
firstRow["status"] = "Pending";
MainWindow.ds.Tables[0].Rows.Add(firstRow);
//MainWindow.ds.Tables[0].AcceptChanges();
//MainWindow.ds.AcceptChanges();
}
}
}
}catch(Exception newToastEntriesException)
{
exceptionCaught = true;
}
if(exceptionCaught)
{
MessageBox.Show("Failed to add current selection to schedule\n Check that a valid date and time is selected", "Error" ,MessageBoxButton.OK ,MessageBoxImage.Asterisk);
}
}
Here's the code running from the window above when I click the Start button
private async void timer_Tick(object sender, EventArgs e)
{
await Task.Run(() => ProcessToastMessages());
}
private void ProcessToastMessages()
{
WindowsToasts.WindowsToast windowsUpdateToast = new WindowsToast(); //creating a new instance of a toast message
int rowCount = 0;
rowCount = ds.Tables[0].Rows.Count;
for (int i = 0; i <= (rowCount - 1); i++)
{
DateTime scheduledTime = DateTime.Now;
//try
//{
DateTime.TryParse(ds.Tables[0].Rows[i]["schedule"].ToString(), out scheduledTime); //Converting the string value of date in the to a type of DateTime
string currentStatus = ds.Tables[0].Rows[i]["status"].ToString();
if ((scheduledTime.Ticks < DateTime.Now.Ticks) && currentStatus == "Pending")
{
string computerName = ds.Tables[0].Rows[i]["hostname"].ToString(); // Gets the computername in currentrow
bool isOnline = ComputerFuncs.ComputerOnline(computerName); // Checking if computer is online (Ping)
switch (isOnline)
{
case true:
//try
//{
ds.Tables[0].Rows[i].SetField("online", true);
//windowsUpdateToast.Send_WindwsUpdateToast(computerName); //Sending toast notification if computer is online
ds.Tables[0].Rows[i].SetField("status", "Sent");
//ds.Tables[0].Rows[i]["status"] = "Sent";
// break;
////}
////catch (Exception psException)
////{
// ds.Tables[0].Rows[i]["online"] = false;
//ds.Tables[0].Rows[i].SetField("online", false);
//ds.Tables[0].Rows[i].SetField("status", "Failed");
// ds.Tables[0].Rows[i]["status"] = "Failed";
// //break;
//}
break;
case false:
ds.Tables[0].Rows[i].SetField("online", false);
break;
}
}
//}
//catch (Exception dateTimeException)
//{
//}
}
}
private void btn_StartStop_Click(object sender, RoutedEventArgs e)
{
// ds.WriteXml((#"C:\temp\ToastData.ds"), XmlWriteMode.WriteSchema);
string btnCurrentText = btn_StartStop.Content.ToString();
if(btnCurrentText == "Start")
{
gridToastItems.IsReadOnly = true;
btn_Schedule.IsEnabled = false;
StartToastMonitoring(true);
}
else if(btnCurrentText == "Stop")
{
StartToastMonitoring(false);
gridToastItems.IsReadOnly = false;
btn_Schedule.IsEnabled = true;
}
}
Error I'm getting is shown below. The iterator seems to be within bounds of the number of rows as far as I can tell.
I have figured what is causing problems. The process of pinging the computers is taking an extreme amount of time if the ping function is unable to get a ping result and a ping exception is thrown.
The interval of the timer had to be increased to allow all the processing to complete. I will figure out another way and try to ping the computers in parallel.
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 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));
}
}
I am working on a c# project and I am trying to create a DataSet and set the itemssource of a datagrid to the dataset.
However, when the grid loads, it shows 4 blank lines (4 records being inside the database) and none of the columns are being shown.
Below is the code for how I am calling the dataset creation function and assign it to the DataGrid.
private void loadData()
{
Classes.SoftwareManager softwareManager = new Classes.SoftwareManager();
DataSet dataSet = softwareManager.getDatasetForSoftware();
if (dataSet != null)
{
softwareGrid.AutoGenerateColumns = false;
dataSet.Tables[0].Columns.RemoveAt(0);
softwareGrid.ItemsSource = dataSet.Tables[0].DefaultView;
}
}
Below is the code that creates the dataset which is returned in the function above.
public DataSet getDatasetForSoftware()
{
DataSet ds = new DataSet();
DataTable table = new DataTable();
DataColumn idCol = new DataColumn();
DataColumn softwareCol = new DataColumn("Software Name");
DataColumn serverCol = new DataColumn("DB Server");
DataColumn userNameCol = new DataColumn("DB Username");
DataColumn passwordCol = new DataColumn("DB Password");
DataColumn portCol = new DataColumn("DB Port");
DataColumn webInstallLocationCol = new DataColumn("Web Install Location");
DataColumn softwareInstallLocationCol = new DataColumn("Software Install Location");
DataColumn startScriptNameCol = new DataColumn("Start Script Name");
DataColumn statusCol = new DataColumn("Status");
idCol.DataType = System.Type.GetType("System.Int32");
softwareCol.DataType = System.Type.GetType("System.String");
serverCol.DataType = System.Type.GetType("System.String");
userNameCol.DataType = System.Type.GetType("System.String");
passwordCol.DataType = System.Type.GetType("System.String");
portCol.DataType = System.Type.GetType("System.String");
webInstallLocationCol.DataType = System.Type.GetType("System.String");
softwareInstallLocationCol.DataType = System.Type.GetType("System.String");
startScriptNameCol.DataType = System.Type.GetType("System.String");
statusCol.DataType = System.Type.GetType("System.String");
table.Columns.Add(idCol);
table.Columns.Add(softwareCol);
table.Columns.Add(serverCol);
table.Columns.Add(userNameCol);
table.Columns.Add(passwordCol);
table.Columns.Add(portCol);
table.Columns.Add(webInstallLocationCol);
table.Columns.Add(softwareInstallLocationCol);
table.Columns.Add(startScriptNameCol);
table.Columns.Add(statusCol);
List<SoftwareDetails> softwareDetails = getSoftwareDetails();
if (softwareDetails != null)
{
foreach (SoftwareDetails software in softwareDetails)
{
DataRow dataRow = table.NewRow();
dataRow[idCol] = software.id;
dataRow[softwareCol] = software.softwareName;
dataRow[serverCol] = software.dbServer;
dataRow[userNameCol] = software.dbUsername;
dataRow[passwordCol] = software.dbPassword;
dataRow[portCol] = software.dbPort;
dataRow[webInstallLocationCol] = software.webInstallLocation;
dataRow[softwareInstallLocationCol] = software.softwareInstallLocation;
dataRow[startScriptNameCol] = software.startScriptName;
dataRow[statusCol] = software.status;
table.Rows.Add(dataRow);
}
}
ds.Tables.Add(table);
return ds;
}
Thanks for any help you can provide.
I see softwareGrid.AutoGenerateColumns = false; If your grid does not contain column definition, you should set
softwareGrid.AutoGenerateColumns = true;