Limit EventLogs by Date - c#

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

Related

C# Adding rows to a DataTable inside a foreach loop

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

c# Save DataGridView to Xml file

This is my button to save file:
private void metroButton12_Click(object sender, EventArgs e) // save
{
DataSet ds = (DataSet)dataGridView1.DataSource;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "XML|*.xml";
if (sfd.ShowDialog() == DialogResult.OK)
{
try
{
ds.Tables[0].WriteXml(sfd.FileName);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
I try to safe my datagridview to XML but nothing happpend when I choose file.
When I start console I see this:
System.NullReferenceException: The object reference was not set to an object instance.
My gridview look like:
ID Name
1 Michale
2 Noob
What am I doing here wrong?.. I saw a lot of thing's on the web but could not find any solutions in stackoverflow and other forums.
Please be patient for newbie guys. Thank you!
To me it sounds like your problem is not where you think it is.
when i start console i see this : System.NullReferenceException: The object reference was not set to an object instance.
To me you are implying that you get the message when you launch the application, not when you click the button. If you get the error before you click, your problem is elsewhere and not in the code snippet you posted. Here is a complete and testable snippet of what you are currently doing.
using System;
using System.Data;
using System.Windows.Forms;
namespace DataGridViewToXML_43053387
{
public partial class Form1 : Form
{
//DataSet theDataSet;
public Form1()
{
InitializeComponent();
InsertDgvIntoForm();
ExportDgvToXML();
}
private void InsertDgvIntoForm()
{
//create a data set
DataSet ds = new DataSet();
//create a data table for the data set
DataTable dt = new DataTable();
//create some columns for the datatable
DataColumn dc = new DataColumn("ItemName");
DataColumn dc2 = new DataColumn("ItemValue");
DataColumn dc3 = new DataColumn("Blah");
DataColumn dc4 = new DataColumn("Bleh");
//add the columns to the datatable
dt.Columns.Add(dc);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
//create 5 rows of irrelevant information
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["ItemName"] = "Item" + i + "Name";
dr["ItemValue"] = "Item" + i + "Value";
dr["Blah"] = "Item" + i + "Blah";
dr["Bleh"] = "Item" + i + "Bleh";
dt.Rows.Add(dr);
}
//add the datatable to the datasource
ds.Tables.Add(dt);
//just because it looks better on my screen
dataGridView1.AutoSize = true;
//make this data the datasource of our gridview
dataGridView1.DataSource = ds.Tables[0];
}
private void ExportDgvToXML()
{
DataTable dt = (DataTable)dataGridView1.DataSource;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "XML|*.xml";
if (sfd.ShowDialog() == DialogResult.OK)
{
try
{
dt.WriteXml(sfd.FileName);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
}
blaze_125 answer didn't help me so I've found this solution:
private void btnXML_Save_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.TableName = "Bank";
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
//if (dataGridView1.Columns[i].Visible) // Add's only Visible columns (if you need it)
//{
string headerText = dataGridView1.Columns[i].HeaderText;
headerText = Regex.Replace(headerText, "[-/, ]", "_");
DataColumn column = new DataColumn(headerText);
dt.Columns.Add(column);
//}
}
foreach (DataGridViewRow DataGVRow in dataGridView1.Rows)
{
DataRow dataRow = dt.NewRow();
// Add's only the columns that you want
dataRow["BLZ"] = DataGVRow.Cells["BLZ"].Value;
dataRow["Test_1"] = DataGVRow.Cells["Test 1"].Value;
dataRow["Test_2"] = DataGVRow.Cells["Test-2"].Value;
dataRow["PIN_TAN_Test_URL"] = DataGVRow.Cells["PIN/TAN-Test URL"].Value;
dt.Rows.Add(dataRow); //dt.Columns.Add();
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
//Finally the save part:
XmlTextWriter xmlSave = new XmlTextWriter(XML_Save_Path_Filename, Encoding.UTF8);
xmlSave.Formatting = Formatting.Indented;
ds.DataSetName = "Data";
ds.WriteXml(xmlSave);
xmlSave.Close();
}
Result will look like this:
<Data>
<Bank>
<BLZ>10000001</BLZ>
<Test_1>server.bank.com</Test_1>
<Test_2>V3.0</Test_2>
<PIN_TAN_Test_URL>https://test.bank.com/</PIN_TAN_Test_URL>
</Bank>
....
<Bank>
<BLZ>12396123</BLZ>
<HBCI_Zugang_DNS>test01.test.com</HBCI_Zugang_DNS>
<HBCI_Version>V3.0</HBCI_Version>
<PIN_TAN_Test_URL>https://test11.test.com</PIN_TAN_Test_URL>
</Bank>
</Data>

Filtering a datagridview that is bound to a dataset with a textbox c#

I'm trying to filter a datagridview that has been bound to a dataset. The thing is, when I type data into my textbox, the app stops and the error is that the column I'm trying to filter doesn't exist. I tried populating the datagridview with a string query and filtering works properly, but I can't update the datagridview (I don't know why). That's why I'm populating it with a dataset instead of the query. Any suggestions? This is what I have:
DataTable dt = new DataTable("Items");
private void LoadDataGrid()
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Items.ItemID AS #, Items.SerialNo AS 'SERIALNO', Items.Description AS DESCRIPTION, Items.MaxVoltage, Items.FrameSize, Items.ArrivalDate, Items.DepartureDate, Items.Notes, Items.MechType, Items.[Fix-Drawout], CONCAT(Location.Rack, Location.Row, Location.Columnn, Location.Position) AS LOCATION, ItemStatus.Description AS STATUS, Type.Description AS TYPE, Manufacturers.Description AS MANUFACTURERS FROM Items INNER JOIN Location ON Items.LocationID = Location.LocationID INNER JOIN ItemStatus ON Items.Status = ItemStatus.StatusID INNER JOIN Type ON Items.TypeID = Type.TypeID INNER JOIN Manufacturers ON Items.ManufacturerID = Manufacturers.ManufacturerID", AEAcnn))
{
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
This is the filter expression I'm using (with a combobox)
private void txtFilter_KeyPress(object sender, KeyPressEventArgs e)
{
if (cmbFilterSearch.Text == "TYPE")
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("TYPE LIKE '%{0}%'", textBox14.Text);
dataGridView1.DataSource = dv.ToTable();
}
}
The app crashes when the column TYPE can't be found, even though the name is actually TYPE.
Try something like this:
if (dt.Rows.Count > 0)
{
string str = string.Format("[TYPE] LIKE '%{0}%'", textBox14.Text.Replace("'", "''"));
dt.CaseSensitive = false;
DataTable dt1 = dt.Select(str).CopyToDataTable();
dataGridView1.DataSource = dt1;
}
Despite the unconventional column names, I don't see anything incorrect with the code if you are getting past filling the data table with the adapter, which apparently is the case since you get no error until the keypress event. Since we can't see the entire context of the code I suspect you are not binding the data you think you are, or the binding is changing somewhere else that you haven't noticed.
See this LINQPad script for proof it works:
Form frm = new Form();
DataTable dt = new DataTable("Items");
DataGridView dataGridView1 = new DataGridView();
TextBox textBox14 = new TextBox();
TextBox cmbFilterSearch = new TextBox();
void Main()
{
PopulateDataTable(dt);
BuildForm(frm, dt);
Application.Run(frm);
}
void BuildForm(Form frm, DataTable dt)
{
frm.Height = 500;
frm.Width = 900;
cmbFilterSearch.Text = "TYPE";
frm.Controls.Add(cmbFilterSearch);
textBox14.Text = "filter...";
textBox14.Location = new Point(0,50);
frm.Controls.Add(textBox14);
textBox14.KeyPress += txtFilter_KeyPress;
dataGridView1.DataSource = dt;
dataGridView1.Location = new Point(0, 80);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.Width = 800;
frm.Controls.Add(dataGridView1);
}
void txtFilter_KeyPress(object sender, KeyPressEventArgs e)
{
if (cmbFilterSearch.Text == "TYPE")
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("TYPE LIKE '%{0}%'", textBox14.Text);
Console.WriteLine(dv.RowFilter);
dataGridView1.DataSource = dv.ToTable();
}
}
void PopulateDataTable(DataTable dt)
{
dt.Columns.Add("#", typeof(int));
dt.Columns.Add("'SERIALNO'", typeof(string));
dt.Columns.Add("DESCRIPTION", typeof(string));
dt.Columns.Add("MaxVoltage", typeof(string));
dt.Columns.Add("FrameSize", typeof(string));
dt.Columns.Add("ArrivalDate", typeof(DateTime));
dt.Columns.Add("DepartureDate", typeof(DateTime));
dt.Columns.Add("Notes", typeof(string));
dt.Columns.Add("MechType", typeof(string));
dt.Columns.Add("Fix-Drawout", typeof(string));
dt.Columns.Add("LOCATION", typeof(string));
dt.Columns.Add("STATUS", typeof(string));
dt.Columns.Add("TYPE", typeof(string));
dt.Columns.Add("MANUFACTURERS", typeof(string));
DataRow row = dt.NewRow();
row[0] = 1;
row[1] = "9083290823";
row[2] = "Mares eat oats";
row[3] = "12v";
row[4] = "60";
row[5] = DateTime.Now;
row[6] = DateTime.Now.AddDays(7);
row[7] = "and does eat oats";
row[8] = "and little lambs";
row[9] = "eat ivy.";
row[10] = "Cancelled";
row[11] = "KEYWORD";
row[12] = "ACME";
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = 2;
row[1] = "43537953";
row[2] = "Mares eat oats";
row[3] = "12v";
row[4] = "60";
row[5] = DateTime.Now;
row[6] = DateTime.Now.AddDays(7);
row[7] = "and does eat oats";
row[8] = "and little lambs";
row[9] = "eat ivy.";
row[10] = "Cancelled";
row[11] = "Reserved Word";
row[12] = "Conglomico";
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = 3;
row[1] = "9083290823";
row[2] = "Mares eat oats";
row[3] = "12v";
row[4] = "60";
row[5] = DateTime.Now;
row[6] = DateTime.Now.AddDays(7);
row[7] = "and does eat oats";
row[8] = "and little lambs";
row[9] = "eat ivy.";
row[10] = "Cancelled";
row[11] = "Identifier";
row[12] = "Enormico";
dt.Rows.Add(row);
}
Try it this way.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataView dv ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds, "Filter DataView");
adapter.Dispose();
command.Dispose();
connection.Close();
dv = new DataView(ds.Tables[0], "Product_Price < = 3000", "Product_Name", DataViewRowState.CurrentRows);
dataGridView1.DataSource = dv;
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

Adding row to bound datagridview from oracle database

I am trying to build datagridview that consist from two part
one part came from database and the other part is collected information about files on local hard disk and show it as one part but I am getting error message that says
Rows cannot be programmatically added to the datagridview rows
collection when the control is data-bound
Note:
knowing That data within datagridview will be used later to modifies data on oracle database
I had upload imag for more understanding the first two column are from database
private void ListFileToBePatched()
{
try
{
string connstr = "data source=orcl;user id=user;password=pwd";
string cmdstr = #"SELECT OFFICE_CODE as ""Office Code"",
IP_ADDRESS as ""Office IP""
FROM table";
string[] array = Directory.GetFiles(SBankfilespath, "*.txt");
using (OracleConnection conn = new OracleConnection(connstr))
using (OracleCommand cmd = new OracleCommand(cmdstr, conn))
{
conn.Open();
OracleTransaction trans = conn.BeginTransaction();
OracleDataReader OraReader = cmd.ExecuteReader();
DataTable dt = new DataTable();
DataColumn OfficeCodecolumn = new DataColumn();
OfficeCodecolumn.DataType = System.Type.GetType("System.String");
OfficeCodecolumn.ColumnName = "Office Code";
dt.Columns.Add(OfficeCodecolumn);
DataColumn OfficeIPcolumn = new DataColumn();
OfficeIPcolumn.DataType = System.Type.GetType("System.String");
OfficeIPcolumn.ColumnName = "Office IP Address";
dt.Columns.Add(OfficeIPcolumn);
DataColumn FileNamecolumn = new DataColumn();
FileNamecolumn.DataType = System.Type.GetType("System.String");
FileNamecolumn.ColumnName = "File Name";
dt.Columns.Add(FileNamecolumn);
DataColumn FullFilePathcolumn = new DataColumn();
FullFilePathcolumn.DataType = System.Type.GetType("System.String");
FullFilePathcolumn.ColumnName = "Full File Path";
dt.Columns.Add(FullFilePathcolumn);
DataColumn DateCreatedcolumn = new DataColumn();
DateCreatedcolumn.DataType = System.Type.GetType("System.String");
DateCreatedcolumn.ColumnName = "Date Created";
dt.Columns.Add(DateCreatedcolumn);
DataColumn Datemodifiedcolumn = new DataColumn();
Datemodifiedcolumn.DataType = System.Type.GetType("System.String");
Datemodifiedcolumn.ColumnName = "Date modified";
dt.Columns.Add(Datemodifiedcolumn);
foreach (string FullFilePath in array)
{
DataRow row = dt.NewRow();
row[2] = Path.GetFileName(FullFilePath);
row[3] = FullFilePath;
row[4] = File.GetCreationTime(FullFilePath);
row[5] = File.GetLastWriteTime(FullFilePath);
dt.Rows.Add(row);
}
dt.Load(OraReader);
DataView view = new DataView(dt);
DGV_PatchStatus.DataSource = view;
}
FileCount.Text = "File Count ( " + DGV_PatchStatus.Rows.Count.ToString() + " )";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You could use the DataTable.NewRow method to add the row to your DataTable.
foreach (string FullFilePath in array)
{
DataRow r = DT.NewRow();
r[0] = Path.GetFileName(FullFilePath);
r[1] = FullFilePath;
r[2] = File.GetCreationTime(FullFilePath);
r[3] = File.GetLastWriteTime(FullFilePath);
}
Then simply bind the DT again as DataSource
DGV_PatchStatus.DataSource = DT;
EDIT:
what I really need is that for each office has list of files
If you have several files for each office-row you should have a look on this Tree-View-Tutorial this might really be helpful to achieve your desired results.
Here is also a Nested-DataGrid-Example that might also be of help. Good luck.
Make Class For your data after reading from db assign data to that object and put object into List afterwards initialize DGV_PatchStatus.DataSource to that list, when you need to add new row simply add data object to that list and re initialize DGV_PatchStatus DataSource

Programatically creating DataSet and setting to DataGrid causing blank rows for the number of records that should be shown

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;

Categories