How to convert datatable to list<> or array? - c#

I want to get all the data from a table using the code below:
CameraBUS cameraBus = new CameraBUS(); //Contain class provider access to DAO for GetByAllCamera.
DataTable dt = cameraBus.Camera_GetByAllCamera(); //select * from table Camera
foreach (DataRow row in dt.Rows)
{
CameraDTO camera = new CameraDTO(row);
if(camera.IDKhuVuc == 4)
{
OpenCamera(camera.ViTri, camera.TaiKhoan, camera.MatKhau, camera.IP);
}
if(camera.IDKhuVuc == 3)
{
OpenCamera(camera.ViTri, camera.TaiKhoan, camera.MatKhau, camera.IP);
}
}
If camera.IDKhuVuc have 7 rows or more. It's always start StartThead1 and my program stop not working.
Example:
My data has 4 rows, but this code can't get 4 rows of 4 cameras. It only opens the first and last cameras.
When I debug my program, it runs 2 rows (rows 2, 3). But when I run my program, it's not opening camera 2 and camera 3.
I think I should use List<> or array. How could I fix this?
Class OpenCamera():
private void OpenCamera(bool position, string username, string password, string ipAddress)
{
if (!position)
{
axLiveX1.IpAddress = ipAddress;
axLiveX1.UserName = username;
axLiveX1.Password = password;
axLiveX1.DataPort = 5550;
axLiveX1.CommandPort = 4550;
axLiveX1.AudioDataPort = 6550;
axLiveX1.DefaultCam = 8;
axLiveX1.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveX1_OnGetPicture);
axLiveX1.AutoLogin = true;
if (axLiveX1.Connect())
{
}
axLiveX1.StartGrapImage(true);
axLiveX2.IpAddress = ipAddress;
axLiveX2.UserName = username;
axLiveX2.Password = password;
axLiveX2.DataPort = 5550;
axLiveX2.CommandPort = 4550;
axLiveX2.AudioDataPort = 6550;
axLiveX2.DefaultCam = 8;
axLiveX2.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveX2_OnGetPicture);
axLiveX2.AutoLogin = true;
axLiveX2.Connect();
axLiveX2.StartGrapImage(true);
}
else
{
axLiveX3.IpAddress = ipAddress;
axLiveX3.UserName = username;
axLiveX3.Password = password;
axLiveX3.DataPort = 5550;
axLiveX3.CommandPort = 4550;
axLiveX3.AudioDataPort = 6550;
axLiveX3.DefaultCam = 8;
axLiveX3.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveX3_OnGetPicture);
axLiveX3.AutoLogin = true;
axLiveX3.Connect();
axLiveX3.StartGrapImage(true);
axLiveX4.IpAddress = ipAddress;
axLiveX4.UserName = username;
axLiveX4.Password = password;
axLiveX4.DataPort = 5550;
axLiveX4.CommandPort = 4550;
axLiveX4.AudioDataPort = 6550;
axLiveX4.DefaultCam = 8;
axLiveX4.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveX4_OnGetPicture);
axLiveX4.AutoLogin = true;
axLiveX4.Connect();
axLiveX4.StartGrapImage(true);
}
}

Try something like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Col A", typeof(int));
dt.Columns.Add("Col B", typeof(int));
dt.Columns.Add("Col C", typeof(int));
dt.Rows.Add(new object[] { 1, 2, 3});
dt.Rows.Add(new object[] { 10, 20, 30 });
dt.Rows.Add(new object[] { 100, 200, 300 });
List<DataRow> rows = dt.AsEnumerable().Select(x => x).ToList();
var numbers = dt.AsEnumerable().Select(x => x.ItemArray).ToList();
}
}
}
​
​
You can get data of any cell like this with your original code
foreach (DataRow row in dt.Rows)
{
string colA = (string)row["Col A"];
}​
To Get entire column try something like this
var colA = dt.AsEnumerable().Select(x => x.Field<string>("Col A")).ToList();​

Related

SSIS Google Analytics api call

I've got some code that I have used to pull Google Analytics data with a c# console application and it works great. Whenever I try to use that same code in an SSIS script task I get the error "Error deserializing JSON credential data.". I get the error when running locally and when deployed. I've got all the libraries added to the GAC and I'm using the same version libraries and .net Framework as the console app. Anyone have any ideas?
public void Main()
{
string SQL_Script = null;
string ErrorMessage = string.Empty;
string ExceptionMessage = "No error";
// Declare the variables that you'll be pulling from Google Analytics into the database
DateTime GA_Session_Date = new DateTime();
DateTime GA_End_Date = new DateTime();
GA_End_Date = DateTime.Today.AddDays(-1);
string GA_TransactionId = null;
string GA_ChannelGrouping = null;
string GA_Source = null;
string GA_Medium = null;
string GA_Keyword = null;
string GA_Campaign = null;
string GA_Device_Category = null;
string GA_Region = null;
int GA_Transactions = 0;
/*
* Get the last SessionDate loaded
*/
GA_Session_Date = Convert.ToDateTime(GetMaxSessionnDate());
GA_Session_Date = GA_Session_Date.AddDays(-1);
/*
* Delete the last SessionDate loaded from the table
*
* The free version of Google Analytics takes up to 24 hours to bake
* so reloading the last day will ensure that we get all of the data.
*/
SQL_Script = "DELETE FROM OmniChannelAnalytics.GoogleAnalytics.Transactions WHERE SessionDate >= '" + GA_Session_Date.ToString() + "';";
ErrorMessage = ExecuteSQL(SQL_Script);
/*
* Create the DataTable and DataSet to house the data from GA until
* it is bulk loaded into SQL
*/
DataSet dataSet = new DataSet();
DataTable sessionTable = new DataTable();
sessionTable.TableName = "Sessions";
// Add the columns to the Sessions table
sessionTable.Columns.Add("SessionDate", typeof(string));
sessionTable.Columns.Add("TransactionId", typeof(string));
sessionTable.Columns.Add("ChannelGrouping", typeof(string));
sessionTable.Columns.Add("Source", typeof(string));
sessionTable.Columns.Add("Medium", typeof(string));
sessionTable.Columns.Add("Keyword", typeof(string));
sessionTable.Columns.Add("Campaign", typeof(string));
sessionTable.Columns.Add("DeviceCategory", typeof(string));
sessionTable.Columns.Add("Region", typeof(string));
sessionTable.Columns.Add("Transactions", typeof(int));
sessionTable.Columns.Add("LoadDate", typeof(string));
dataSet.Tables.Add(sessionTable);
while (GA_Session_Date <= GA_End_Date)
{
try
{
var credential = Google.Apis.Auth.OAuth2.GoogleCredential.FromFile(GlobalVariables.GA_ClientSecretFileLocation)
.CreateScoped(new[] { Google.Apis.AnalyticsReporting.v4.AnalyticsReportingService.Scope.AnalyticsReadonly });
using (var analytics = new Google.Apis.AnalyticsReporting.v4.AnalyticsReportingService(new Google.Apis.Services.BaseClientService.Initializer
{
HttpClientInitializer = credential
}))
{
var request = analytics.Reports.BatchGet(new GetReportsRequest
{
ReportRequests = new[] {
new ReportRequest{
DateRanges = new[] { new DateRange{ StartDate = GA_Session_Date.ToString("yyyy-MM-dd"), EndDate = GA_Session_Date.ToString("yyyy-MM-dd") } },
Dimensions = new[] {
new Dimension{ Name = "ga:transactionId" }
, new Dimension { Name = "ga:channelGrouping" }
, new Dimension { Name = "ga:sourceMedium" }
, new Dimension { Name = "ga:keyword" }
, new Dimension { Name = "ga:campaign" }
, new Dimension { Name = "ga:deviceCategory" }
, new Dimension { Name = "ga:region" }
},
Metrics = new[] { new Metric{ Expression = "ga:transactions", Alias = "Transactions"}},
ViewId = GlobalVariables.GA_View_ID
}
}
});
var response = request.Execute();
foreach (var row in response.Reports[0].Data.Rows)
{
GA_TransactionId = row.Dimensions[0];
GA_ChannelGrouping = row.Dimensions[1];
GA_Source = row.Dimensions[2].Substring(0, row.Dimensions[2].IndexOf("/")).Trim().Replace("'", "''");
GA_Medium = row.Dimensions[2].Substring(row.Dimensions[2].IndexOf("/") + 1, row.Dimensions[2].Length - row.Dimensions[2].IndexOf("/") - 1).Trim().Replace("'", "''");
GA_Keyword = row.Dimensions[3];
GA_Campaign = row.Dimensions[4];
GA_Device_Category = row.Dimensions[5];
GA_Region = row.Dimensions[6];
foreach (var metric in row.Metrics)
{
GA_Transactions = Convert.ToInt32(metric.Values[0]);
}
// Populate the data table to hold until everything is bulk loaded into SQL
DataRow newRow = sessionTable.NewRow();
newRow["SessionDate"] = GA_Session_Date;
newRow["TransactionId"] = GA_TransactionId;
newRow["ChannelGrouping"] = GA_ChannelGrouping;
newRow["Source"] = GA_Source;
newRow["Medium"] = GA_Medium;
newRow["Keyword"] = GA_Keyword;
newRow["Campaign"] = GA_Campaign;
newRow["DeviceCategory"] = GA_Device_Category;
newRow["Region"] = GA_Region;
newRow["Transactions"] = GA_Transactions;
newRow["LoadDate"] = DateTime.Now;
sessionTable.Rows.Add(newRow);
} // foreach (var row in rows)
}
} // try
catch (Exception ex)
{
ExceptionMessage = ex.Message;
}
finally
{
// Import the current day's Session data
foreach (DataTable table in dataSet.Tables)
{
ImportTable(table);
}
sessionTable.Clear();
}
// Iterate the session date to import by 1
GA_Session_Date = GA_Session_Date.AddDays(1);
} // while (GA_Session_Date <= GA_End_Date)
Dts.TaskResult = (int)ScriptResults.Success;
}

Difficulties with C# + Excel

I have a problem.
I have an Excel File where sometimes the same customer is in 2 rows.
But not always.
Its like:
Click
Now, i want to create a DataGrid in C# which can list this in one row like:
Click
I know it would be easier to change the Excel file, but assume it wouldnt work that way(we get the file like this and we cant change it)
I know i could too just make another Excel File and make it with Excel(already did it this way, but we would need it more as C#)
Now i am at this point:
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Arbeitsmappe |*.xlsx", ValidateNames = true };
if (ofd.ShowDialog() == DialogResult.OK)
textBox1.Text = ofd.SafeFileName;
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = false;
string filename = ofd.FileName;
Excel.Workbook workbook = excelApp.Workbooks.Open(filename);
Excel.Worksheet worksheet = workbook.Worksheets[1];
dataGridView1.ColumnCount = 2;
dataGridView1.Columns[0].Name = "Number";
dataGridView1.Columns[1].Name = "Street";
int rows = worksheet.UsedRange.Rows.Count;
for (int i = 2; i <= rows; i++)
{
string combinehr = worksheet.Cells[i, 150].Text + worksheet.Cells[i, 151].Text;
dataGridView1.Rows.Add(worksheet.Cells[i,29].Text, combinehr);
}
}
How do i expand it that it works like i want?
I would be so grateful
(sorry for the english)
With a reference to ExcelDataReader, ExcelDataReader.DataSet and DataSetExtensions (.Net) you can read the Excel file pretty easy into a DataSet, then you just have to work with the logic:
Input file:
using System;
using System.Data;
using System.IO;
using System.Linq;
using ExcelDataReader;
public DataTable GetTableFromExcel(string filePath)
{
DataSet ds = new DataSet();
using (var stream = System.IO.File.Open(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
ds = reader.AsDataSet();
}
}
DataTable table = new DataTable();
table.Columns.Add(new DataColumn("CustomerNr"));
table.Columns.Add(new DataColumn("Address"));
// Set column names
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
// DataColumn.ColumnName can't be empty when DataColumn is part
// of a DataTable (throws ArgumentException)
string columnName = ds.Tables[0].Rows[0][i].ToString();
if (string.IsNullOrWhiteSpace(columnName))
{
columnName = $"Column{i}";
}
ds.Tables[0].Columns[i].ColumnName = columnName;
}
// Remove the first row containing the headers
ds.Tables[0].Rows.Remove(ds.Tables[0].Rows[0]);
// I don't have the benchmarks with me right now, but I've tested
// DataTable.Select vs DataTable.AsEnumerable.Select many times
// and the AsEnumerable method its faster, that's why you need the
// reference to System.Data.DataSetExtensions
var enumerableTable = ds.Tables[0].AsEnumerable();
// list of unique products
var products = enumerableTable.Select(row => row.Field<string>("Product")).Distinct();
// Add a column for each product
foreach (string product in products)
{
table.Columns.Add(new DataColumn(product));
}
// list of unique customers
var customerNumbers = enumerableTable.Select(row => row.Field<double>("CustomerNr")).Distinct();
foreach (var customerNumber in customerNumbers)
{
DataRow record = table.NewRow();
record["CustomerNr"] = customerNumber;
record["Address"] = enumerableTable.First(row => row.Field<double>("CustomerNr").Equals(customerNumber))[1];
for (int i = 2; i < table.Columns.Count; i++)
{
DataRow product = enumerableTable.FirstOrDefault(row => row.Field<double>("CustomerNr").Equals(customerNumber)
&& row.Field<string>("Product").Equals(table.Columns[i].ColumnName));
// Quantity = 0 if product is null
record[i] = product?["Quantity"] ?? 0;
}
table.Rows.Add(record);
}
return table;
}
Result DataTable:
The same result as #IvanGarcíaTopete via Microsoft.Office.Interop.Excel.
Class ExcelModel for Excel data:
public class ExcelModel
{
public string CustomerNr { get; set; }
public string Address { get; set; }
public string Product { get; set; }
public string Quantity { get; set; }
}
Read Excel and fill out model:
private void OpenReadExcel()
{
var dlg = new OpenFileDialog();
if (dlg.ShowDialog() != DialogResult.OK) return;
var exApp = new Microsoft.Office.Interop.Excel.Application();
Workbook exWbk = exApp.Workbooks.Open(dlg.FileName);
Worksheet wSh = exWbk.Sheets[1];
int k = 2;
Customers.Clear();
while (wSh.Cells[k, 1].Text != "" && wSh.Cells[k, 1].Value != null)
{
var rowExcelModel = new ExcelModel()
{
CustomerNr = wSh.Cells[k, 1].Text,
Address = wSh.Cells[k, 2].Text,
Product = wSh.Cells[k, 3].Text,
Quantity = wSh.Cells[k, 4].Text
};
Customers.Add(rowExcelModel);
k++;
}
exApp.Quit();
}
Generate Data table:
private void GenerateDataTable()
{
// unique products and customers
var products = Customers.Select(x => x.Product).Distinct().ToList();
var customers = Customers.Select(x => x.CustomerNr).Distinct().ToList();
// columns CustomerNr and Address
var dataTable = new System.Data.DataTable();
dataTable.Columns.Add(new DataColumn("CustomerNr"));
dataTable.Columns.Add(new DataColumn("Address"));
// columns for each product
foreach (var product in products)
{
dataTable.Columns.Add(new DataColumn(product));
}
//fill rows for each customers
foreach (var customer in customers)
{
var row = dataTable.NewRow();
row["CustomerNr"] = customer;
row["Address"] = Customers.Where(x => x.CustomerNr == customer).Select(x => x.Address).FirstOrDefault();
foreach (var product in products)
{
var quantity = Customers.Where(x => x.CustomerNr == customer && x.Product == product)
.Select(x => x.Quantity).FirstOrDefault();
row[product] = quantity ?? "0";
}
dataTable.Rows.Add(row);
}
dataGridView1.DataSource = dataTable;
}

How to update datagridview with multithreading

i'm new to this multithreading concept and have spent lot of time doing my RnD but not able to get thing done. What I'm trying to do is similar to trading applications . I have A datagridview in windows form showing multiple records in it coming from sql database. it has 4 columns(decimal values).I also have txt files which are updated every minute. I have to read latest line from txt file and compare a decimal values from this line to every decimal column in datagridview. Based on this comparison i'm trying to change color of gridview cells. I find my code logically correct but somehow it's not working.For every row in grid one thread should start but only one thread is started that is for last record in grid.I have attached my code .please help me with this.
**InitiateAlert :: It should loop over grid and start a new thread for each record.
checkiftargetreached :: Each Thread should call this function with parameters. Here the comparison of decimal values is doen and grid cell color is set.**
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace MultithredingSample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnshow_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("MyTable");
dt.Columns.Add(new DataColumn("id", typeof(int)));
dt.Columns.Add(new DataColumn("Val1", typeof(decimal)));
dt.Columns.Add(new DataColumn("Val2", typeof(decimal)));
dt.Columns.Add(new DataColumn("Val3", typeof(decimal)));
dt.Columns.Add(new DataColumn("Flag", typeof(Boolean)));
DataRow dr = dt.NewRow();
dr["id"] = 1;
dr["Val1"] = 23104.10;
dr["Val2"] = 23154.10;
dr["Val3"] = 23845.45;
dr["Flag"] = true;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["id"] = 2;
dr["Val1"] = 25104.10;
dr["Val2"] = 25154.10;
dr["Val3"] = 25845.45;
dr["Flag"] = true;
dt.Rows.Add(dr);
dataGridView1.DataSource = dt;
}
private void checkiftargetreached(Int32 rowid,decimal val1,decimal val2, decimal val3, string filepath)
{
string line;
try
{
while (Convert.ToInt16(this.dataGridView1.Rows[rowid].Cells["Flag"].Value) == 1)
{
FileStream fs = new FileStream("C:\\Users\\username\\Downloads\\" + filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs);
DataTable dtrec = new DataTable();
line = sr.ReadLine();
string[] values = line.Split(',');
for (int i = 0; i <= values.Length - 1; i++)
{dtrec.Columns.Add(values[i]);}
line = sr.ReadLine();
DataRow dr = dtrec.NewRow();
string[] values2 = line.Split(',');
for (int i = 0; i <= values2.Length - 1; i++)
{dr[i] = values2[i];}
dtrec.Rows.Add(dr);
if(Convert.ToDecimal(dtrec.Rows[0][1]) == Convert.ToDecimal(this.dataGridView1.Rows[rowid].Cells["Val1"].Value))
{
if (this.dataGridView1.InvokeRequired){
this.dataGridView1.BeginInvoke((MethodInvoker)delegate () { this.dataGridView1.Rows[rowid].Cells["Val1"].Style.BackColor = Color.Aqua; });
}
}
else if (Convert.ToDecimal(dtrec.Rows[0][1]) == Convert.ToDecimal(this.dataGridView1.Rows[rowid].Cells["Val2"].Value))
{
if (this.dataGridView1.InvokeRequired)
{
this.dataGridView1.BeginInvoke((MethodInvoker)delegate () { this.dataGridView1.Rows[rowid].Cells["Val2"].Style.BackColor = Color.Aqua; this.dataGridView1.Rows[rowid].Cells["Flag"].Value = 0; });
}
}
else if (Convert.ToDecimal(dtrec.Rows[0][1]) == Convert.ToDecimal(this.dataGridView1.Rows[rowid].Cells["Val3"].Value))
{
if (this.dataGridView1.InvokeRequired)
{
this.dataGridView1.BeginInvoke((MethodInvoker)delegate () { this.dataGridView1.Rows[rowid].Cells["Val3"].Style.BackColor = Color.Aqua; });
}
}
else
{
if (this.dataGridView1.InvokeRequired)
{
this.dataGridView1.BeginInvoke((MethodInvoker)delegate () { this.dataGridView1.Rows[rowid].Cells["Val3"].Style.BackColor = Color.IndianRed; });
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void InitiateAlerts()
{
Int32 row;
decimal val1, val2, val3;
try
{
for (int j = 0; j <= dataGridView1.Rows.Count - 1; j++)
{
if (this.dataGridView1.InvokeRequired)
{
this.dataGridView1.BeginInvoke((MethodInvoker)delegate ()
{
if (Convert.ToInt16(this.dataGridView1.Rows[j].Cells["Flag"].Value) == 1)
{
row = j;
val1 = Convert.ToDecimal(this.dataGridView1.Rows[row].Cells["Val1"].Value);
val2 = Convert.ToDecimal(this.dataGridView1.Rows[row].Cells["Val2"].Value);
val3 = Convert.ToDecimal(this.dataGridView1.Rows[row].Cells["Val3"].Value);
Thread TH = new Thread(() => checkiftargetreached(row, val1, val2, val3, "A" + row.ToString() + ".txt"));
TH.Name = "A" + row.ToString() + ".csv";
TH.Start();
}
});
}
else
{
if (Convert.ToInt16(this.dataGridView1.Rows[j].Cells["Flag"].Value) == 1)
{
row = j;
val1 = Convert.ToDecimal(this.dataGridView1.Rows[row].Cells["Val1"].Value);
val2 = Convert.ToDecimal(this.dataGridView1.Rows[row].Cells["Val2"].Value);
val3 = Convert.ToDecimal(this.dataGridView1.Rows[row].Cells["Val3"].Value);
Thread TH = new Thread(() => checkiftargetreached(row, val1, val2, val3, "A" + row.ToString() + ".txt"));
TH.Name = "A" + row.ToString() + ".csv";
TH.Start();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnthread_Click(object sender, EventArgs e)
{
InitiateAlerts();
}
}
}
Here is a tutorial from microsoft.
MS says you need to use "virtualmode"
https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/implementing-virtual-mode-wf-datagridview-control#code-snippet-1

c# - DataGridView add row runtime error cell's model

I have a DataGridView component that I use to show some value to the user. It is made of 5 columns: 4 strings and 1 check box. This is my code to create columns and add them to the conrtol:
// class variables
const int NUM_COLUMNS = 5;
DataGridViewColumn[] columns;
DataGridViewCheckBoxColumn checkColumn;
List <String> columnsHeaderName;
// init method
private void init_dataGridView()
{
// init all components
columnsHeaderName = new List<string>();
columns = new DataGridViewColumn[NUM_COLUMNS - 1]; // minus one becouse last one is a check box column
checkColumn = new DataGridViewCheckBoxColumn(); // last one
// columns descriptions
columnsHeaderName.Add("File path");
columnsHeaderName.Add("Sampling");
columnsHeaderName.Add("Start Date");
columnsHeaderName.Add("End Date");
columnsHeaderName.Add("Select");
for (int i = 0; i < NUM_COLUMNS - 1; i++)
{
// create, configure and add n-1 columns
columns[i] = new DataGridViewColumn();
columns[i].Name = Convert.ToString(i);
columns[i].HeaderText = columnsHeaderName[i];
columns[i].ReadOnly = true;
this.dataGridView1.Columns.Add(columns[i]);
}
// create, configure and add last column
checkColumn.Name = Convert.ToString(NUM_COLUMNS - 1);// (NUM_COLUMNS - 1).ToString();
checkColumn.HeaderText = columnsHeaderName[NUM_COLUMNS - 1];
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
this.dataGridView1.Columns.Add(checkColumn);
}
The problem appears when I try to add a new row to my table
private void LoadFileButton_Click(object sender, EventArgs e)
{
string file = "";
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
file = openFileDialog1.FileName;
Console.WriteLine(file);
dataGridView1.Rows.Add(new object[] { "value 1", "value 2", "value 3", "value 4", true });
}
}
The call to dataGridView1.Rows.Add() method throws me an exception. The description of the exception is: "At least one of the columns has not any cell's model"
Really I don't understand what I am doing wrong. Hope some ine can help me. Thanks in advance.
You cannot add DataGridViewColumn
If you try and run below code:
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.Name = "xyz";
col.HeaderText = "XYZ";
col.ReadOnly = true;
this.dataGridView1.Columns.Add(col);
It will work because we are adding DataGridViewTextBoxColumn not DataGridViewColumn
So possible fix is
for (int i = 0; i < NUM_COLUMNS - 1; i++)
{
// create, configure and add n-1 columns
columns[i] = new DataGridViewTextBoxColumn(); // or some other type that you want
columns[i].Name = Convert.ToString(i);
columns[i].HeaderText = columnsHeaderName[i];
columns[i].ReadOnly = true;
this.dataGridView1.Columns.Add(columns[i]);
}
Try this
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace stackkcw
{
public partial class Form1 : Form
{
public TcpClient client;
private DataGridView datgdStock;
private TextBox lablUpdates;
private TextBox lablTime;
private int countOfData;
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
init_dataGridView();
}
const int NUM_COLUMNS = 5;
DataGridViewColumn[] columns;
DataGridViewCheckBoxColumn checkColumn;
List<String> columnsHeaderName;
// init method
private void init_dataGridView()
{
dt.Columns.Add("File path", typeof(string));
dt.Columns.Add("Sampling", typeof(decimal));
dt.Columns.Add("Start Date", typeof(DateTime));
dt.Columns.Add("End Date", typeof(DateTime));
dt.Columns.Add("Select", typeof(Boolean));
dt.Rows.Add(new object[] { "c:\\", 123.45, DateTime.Parse("1/1/2017"), DateTime.Parse("1/2/2017"), true });
dt.Rows.Add(new object[] { "c:\\", 123.46, DateTime.Parse("1/8/2017"), DateTime.Parse("1/9/2017"), false });
dt.Rows.Add(new object[] { "c:\\", 123.47, DateTime.Parse("1/15/2017"), DateTime.Parse("1/16/2017"), true });
dt.Rows.Add(new object[] { "c:\\", 123.48, DateTime.Parse("1/22/2017"), DateTime.Parse("1/23/2017"), false });
dt.Rows.Add(new object[] { "c:\\", 123.49, DateTime.Parse("1/29/2017"), DateTime.Parse("1/30/2017"), true });
dataGridView1.DataSource = dt;
}
}
}

C# Read a particular value from CSV file [duplicate]

This question already has answers here:
Reading CSV file and storing values into an array
(21 answers)
Closed 8 years ago.
I am a learner in C#. I want to read a particular value from the CSV file. I have learned the getting the csv file into a datatable through browsing. Please see the following code (Thanks to surendra jha) and my CSV file format. Say, I want to get what is the 'Volume' for 'ID' = 90.
CSV file
ID:Volume:Name
100:5600:A
95:5000:B
90:4500:C
85:4000:D
Code for getting all the values:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
namespace DVHConsolePrj
{
class Program
{
static void Main(string[] args)
{
readCsvFileData();
}
static void readCsvFileData()
{
string path = #"C:\IDVolumeName.txt";
StreamReader streamreader = new StreamReader(path);
DataTable datatable = new DataTable();
int rowcount = 0;
string[] columnname = null;
string[] streamdatavalue = null;
while (!streamreader.EndOfStream)
{
string streamrowdata = streamreader.ReadLine().Trim();
if (streamrowdata.Length > 0)
{
streamdatavalue = streamrowdata.Split(':');
if (rowcount == 0)
{
rowcount = 1;
columnname = streamdatavalue;
foreach (string csvheader in columnname)
{
DataColumn datacolumn = new DataColumn(csvheader.ToUpper(), typeof(string));
datacolumn.DefaultValue = string.Empty;
datatable.Columns.Add(datacolumn);
}
}
else
{
DataRow datarow = datatable.NewRow();
for (int i = 0; i < columnname.Length; i++)
{
datarow[columnname[i]] = streamdatavalue[i] == null ? string.Empty : streamdatavalue[i].ToString();
}
datatable.Rows.Add(datarow);
}
}
}
streamreader.Close();
streamreader.Dispose();
foreach (DataRow dr in datatable.Rows)
{
string rowvalues = string.Empty;
foreach (string csvcolumns in columnname)
{
rowvalues += csvcolumns + "=" + dr[csvcolumns].ToString() + " ";
}
Console.WriteLine(rowvalues);
}
Console.ReadLine();
}
}
}
Instead of parsing the file manually in a DataTable, then doing some Linq, use Linq directly on it, using this library.
It works pretty well and is very efficient with big files.
For instance.
1) Add nuget package in your project, and the following line to be able to use it:
using LINQtoCSV;
2) define the class that olds the data
public class IdVolumeNameRow
{
[CsvColumn(FieldIndex = 1)]
public string ID { get; set; }
[CsvColumn(FieldIndex = 2)]
public decimal Volume { get; set; }
[CsvColumn(FieldIndex = 3)]
public string Name{ get; set; }
}
3) and search for the value
var csvAttributes = new CsvFileDescription
{
SeparatorChar = ':',
FirstLineHasColumnNames = true
};
var cc = new CsvContext();
var volume = cc.Read<IdVolumeNameRow>(#"C:\IDVolumeName.txt", csvAttributes)
.Where(i => i.ID == "90")
.Select(i => i.Volume)
.FirstOrDefault();
public DataTable CSVToDataTable(string filename, string separator)
{
try
{
FileInfo file = new FileInfo(filename);
OleDbConnection con =
new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
file.DirectoryName + "\";
Extended Properties='text;HDR=Yes;FMT=Delimited(" + separator + ")';")
OleDbCommand cmd = new OleDbCommand(string.Format
("SELECT * FROM [{0}]", file.Name), con);
con.Open();
DataTable tbl = new DataTable();
using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
{
tbl = new DataTable("MyTable");
adp.Fill(tbl);
}
return tbl;
}
catch(Exception ex)
{
throw ex;
}
finally()
{
con.Close();
}
}
You can try this code, it is build on the fly, it is possible little errors to exist. Check OleDbConnection. When you return the DataTable you can search in the table using LINQ.
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("ID") == 90
select myRow;
Here you can take the row with ID=90 !
For filtering DataTable you can use DataTable.Select method like this
var filtered = dataTable.Select("ID = '90'");
filtered above is array of datarow that suitable for the condition, so for get value from first filtered row you can use something like
if(filtered.Length>0){
var Volume = filtered[0]["VOLUME"];
}

Categories

Resources