search in a Datatable - c#

I am currently working on a project that processing a file and create a datatble and create a "excel" look data grid view for the processed results.
The flow is open a new file and click process. After that, the datagridview will show a table with processed data. The following is the function to create a table and input the values for each columns.
public DataTable createDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("Date Time");
dt.Columns.Add("CAT Protocol");
dt.Columns.Add("Display");
//dt.Columns.Add("Command ID");
dt.Columns.Add("Command Description");
List<string> timeList = time();
List<string> catList = read(userSelectedFilePath);
List<string> displayList = translate(catList);
List<string> idList = commandID(catList);
List<string> descList = commandDescription(idList);
int rows = catList.Count();
for (int i = 0; i < rows; i++)
{
DataRow _myRow = dt.NewRow();
_myRow["Date Time"] = timeList.ElementAt(i);
_myRow["CAT Protocol"] = catList.ElementAt(i);
_myRow["Display"] = displayList.ElementAt(i);
//_myRow["Command ID"] = idList.ElementAt(i);
_myRow["Command Description"] = descList.ElementAt(i);
dt.Rows.Add(_myRow);
}
return dt;
}
Then the user can use "Find" function which will refresh the results based on the users' input. When user choose Find, a textbox will pop out. When user press enter, the datatable will be refreshed based on Command Description.
I think I need to write some code in this function.
private void TextBoxKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//write something here
}
}
Here is the screenshot of my interface.
My question is how to implement find function in this application. I will really appreciate all kinds of help. Thanks!

You could use LINQ to get all your indices of the corresponding lines:
var indices = descList.Select((desc, index) => new { desc, index = index }).Where(item => item .desc.Contains(SearchTextBox.Text)).Select(item => item.index).ToList();
Then clear your DataGridViewand readd all those items with the indices, you get.
for (int i = 0; i < indices.Count; i++)
{
DataRow _myRow = dt.NewRow();
_myRow["Date Time"] = timeList.ElementAt(indices[i]);
_myRow["CAT Protocol"] = catList.ElementAt(indices[i]);
_myRow["Display"] = displayList.ElementAt(indices[i]);
//_myRow["Command ID"] = idList.ElementAt(indices[i]);
_myRow["Command Description"] = descList.ElementAt(indices[i]);
dt.Rows.Add(_myRow);
}
Furthermore I'd suggest you build a class for each row:
public class LogLine{
public DateTime Date {get;set;} //maybe Convert to DateTime or change to string
public string Protocol {get;set;}
public string Display {get;set;}
public string Command {get;set;}
}
Later you can simply use List<LogLine> to populate your DataGridView.
This will make your code cleaner, and will simplify much of the code.

Related

I need helping adding two different rows(with same columns) to the same datatable

Working on a windows form application that reads in data from csv files and adds the data to a Datagridview. I ran into an issue with all of the rows being added to the datable and being displayed on the datagridview. The datagridview displays the datarows from the first two if conditions and OneRow if condition only. It will not add the rows from the twoRow if condition if the datable and datagridview rows are populated with the OneRow if condition rows. But i want the rows from both OneRow and TwoRow to be displyed. Also the rows from TwoRow do populate the datatable and datagridview when I comment(/**/) out the OneRow if condition. But I need both to populate the table. Thanks in advance!
Construct.MainDataTable.Columns.Add("Date", typeof(DateTime));
Construct.MainDataTable.Columns.Add("Time");
Construct.MainDataTable.Columns.Add("Serial");
Construct.MainDataTable.Columns.Add("Type");
Construct.MainDataTable.Columns.Add("level");
Construct.MainDataTable.Columns.Add("price");
Construct.MainDataTable.Columns.Add(" Limit");
Construct.MainDataTable.Columns.Add("last Limit");
Construct.MainDataTable.Columns.Add("Data");
..........................
...............................................
DataRow oneRow = Construct.MainDataTable.NewRow();
DataRow twoRow = Construct.MainDataTable.NewRow();
dataGridView2.AllowUserToAddRows = false;
if (line.Split(',')[2].Equals("Time"))
{
time = line.Split(',')[3];
date = line.Split(',')[1];
}
if (line.Split(',')[2].Equals("Level"))
{
level = line.Split(',')[3];
}
//OneROw(IF condition)
if ((Convert.ToDecimal(line.Split(',')[8])) < (Convert.ToDecimal (line.Split(',')[12])))
{
type = line.Split(',')[1];
serial = line.Split(',')[7];
price = line.Split(',')[3];
Limit = line.Split(',')[8];
lastLimit = line.Split(',')[10];
Data = line.Split(',')[12];
oneRow["Date"] = date;
oneRow["Time"] = time;
oneRow["Serial"] = serial;
oneRow["Type"] = type;
oneRow["level"] = level;
oneRow["price"] = price;
oneRow[" Limit"] = Limit;
oneRow["last Limit"] = lastlimit;
oneRow["Data"] = Data;
Construct.MainDataTable.Rows.Add(oneRow);
}
//TwoROw(IF condition)
if ((line.Contains('"')) && ((line.Contains("NG"))))
{
price = line.Split(',')[3];
type = line.Split(',')[1];
serial = line.Split(',')[7];
Limit = line.Split('"')[7];
var valLimit = Limit.Split(',').Select(a => Convert.ToInt32(a, 16));
var limitJoin = String.Join(",", valLimit);
lastlimit = line.Split('"')[1];
var vallastLimit = lastlimit.Split(',').Select(d => Convert.ToInt32(d, 16));
var lastJoin = String.Join(",", vallastLimit);
Data = line.Split('"')[5];
var valDatas = Data.Split(',').Select(s => Convert.ToInt32(s, 16));
var dataJoin = String.Join(",", valDatas);
twoRow["Date"] = date;
twoRow["Time"] = time;
twoRow["Serial"] = serial;
twoRow["Type"] = type;
twoRow["level"] = level;
twoRow["price"] = price;
twoRow["Limit"] = limitJoin;
twoRow["last Limit"] = lastJoin;
twoRow["Data"] = dataJoin;
Construct.MainDataTable.Rows.Add(twoRow);
}
dataGridView2.DataSource = Construct.MainDataTable;
Can't add a comment because I don't have enough karma so I ask my questions here: So, if I understood your problem you can't add data from one .csv file if it have more then one row? Why are you using 2 different if conditions for row in .csv file?
If you have empty data in row never mind you can still place them to your DataTable column, so you can use loop to add data from .csv to your DataTable. Try some thing like this:
public static DataTable CsvToDataTable(string csv)
{
DataTable dt = new DataTable();
string[] lines = csv.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
Regex onlyDeimiterComma = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
for (int i = 0; i < lines.Length; i++)
{
DataRow row = dt.NewRow();
string[] cells = onlyDeimiterComma.Split(lines[i]);
for (int j = 0; j < cells.Length; j++)
{
if (i == 0)
{
if (j == 0)
{
dt.Columns.Add(cells[j], typeof(DateTime));
}
else
{
dt.Columns.Add(cells[j]);
}
}
else
{
row[j] = cells[j];
}
}
dt.Rows.Add(row);
}
return dt;
}
Just call this method anywhere in your code and give it string read from your .csv file.
You can try to compile this code here and see how it works on .csv data with different data (empty columns, quoted text, quoted commas)
UPD: If you need to fill DataTable from two different .csv files you can still use code above. Just call it twice for both files and then Merge two DataTable, like this:
DataTable dt = CsvToDataTable(csvFileOne);
DataTable dtTwo = CsvToDataTable(csvFileTwo);
dt.Merge(dtTwo);

My method for comparing DateTime doesn't work

So, I'm making a small version of library inventory manager. I have a method that should call the database, take one DateTime values and compare it with today's date. I have a table with rented books and in every row there is a "rented_till" value. My loop should go through every row and my method should compare those values. The problem is that it doesn't work and even my flags are not working
I tried to use breaking points but even their I can see that compailer skips my code.
This is something new for me, since I never done that some maybe I'm doing something completley wrong. I couldn't find a similary problem. You can see my method below.
public void CheckBooks()
{
OverdueBooksDAL obDAL = new OverdueBooksDAL();
DataTable dt = new DataTable();
dt = obDAL.RentedBooks();
int rows = dt.Rows.Count;
DateTime today = DateTime.Now;
for (int i = 0; i < rows; i++)
{
DateTime rented_till = Convert.ToDateTime(dt.Rows[i]["rented_till"]);
int result = DateTime.Compare(today, rented_till);
if (result > 0)
{
OverdueBook OB = new OverdueBook();
OB.Id = Int32.Parse(dt.Rows[i]["id"].ToString());
OB.Title = dt.Rows[i]["title"].ToString();
OB.Rented_Till = Convert.ToDateTime(dt.Rows[i]["rented_till"]);
string fullname = dt.Rows[i]["name"].ToString() + dt.Rows[i]["surname"].ToString();
OB.Rented_By = fullname;
OverdueBooksDAL obeDAL = new OverdueBooksDAL();
if (obeDAL.InsertOverduebooks(OB))
{
MessageBox.Show("There are new books overdue");
}
}
}
Program compiles and every other part of it works. I've checked the tables and they're getting the data from the data base.

Datagrid filter on column that between two age range

I have a datagridview with a column of type string that display values for age ranges such as:
0-18
19-100
0-100
I also have a filter textbox that would need to filter on the age range
(dgv1.DataSource as DataTable).DefaultView.RowFilter =
string.Format("AgeRange LIKE '%{0}' OR AgeRange LIKE '{0}%'", textBoxFilter.Text);
The problem is that if the user enter a number like 18, the grid does not return row for 0-100
How can I get the datagrid to return both 0-18 and 0-100?
I do not think you will be able to do this using the “LIKE” comparator since the values you are looking for are “numeric”. To get the filter you are looking for, you will need a filter with “>=” and “<=” to see if the target age is in the range. It is unclear how the data is originally received, if the “age range” in each row is a string as shown, then I suggest a couple of different hacky ways. In addition, it is unclear what other columns would be in the grid.
One “hacky” approach, would be to make a method that returns a new DataTable with only the rows that fall into the given target range. To help in this endeavor, a second method that takes an int (target value we are looking for), and a DataRowView (The AgeRange we are comparing the “target” value to). This “AgeRange” will be in the rows first column. Here we simply take that string range (“0-18”) and the target value (“18”) to see if this target value IS in the range, then return true or false depending on the result. This can be done using the string.split method to split the “AgeRange” string and int.TryParse to convert the strings into numbers. Below is an example of this.
private bool TargetIsInRange(int target, DataRowView row) {
if (row.Row.ItemArray[0] != null) {
string cellValue = row.Row.ItemArray[0].ToString();
string[] splitArray = cellValue.Split('-');
int startValue;
int endValue;
if (!int.TryParse(splitArray[0], out startValue)) {
return false;
}
if (!int.TryParse(splitArray[1], out endValue)) {
return false;
}
if (target >= startValue && target <= endValue)
return true;
}
return false;
}
The method above should come in handy when looping through the grids rows to figure out which rows go into the new filter DataTable. Next, a method that does this looping through the grid and returns a filtered DataTable. For each row in the grid, we could call the above method and add the rows that return true.
private DataTable GetFilterTable() {
DataTable filterTable = ((DataTable)dgv1.DataSource).Clone();
dgv1.DataSource = gridTable;
int targetValue = -1;
if (int.TryParse(textBox1.Text, out targetValue)) {
foreach (DataGridViewRow row in dgv1.Rows) {
DataRowView dataRow = (DataRowView)row.DataBoundItem;
if (dataRow != null) {
if (TargetIsInRange(targetValue, dataRow)) {
filterTable.Rows.Add(dataRow.Row.ItemArray[0]);
}
}
}
}
return filterTable;
}
It is unclear where you are calling this filter, if you are filtering “strings” then as the user types the filter string in the text box the grid will filter with each character pressed by the user. This is nice with strings, however, in this case using “numbers”, I am guessing a button would be more appropriate. I guess this is something that you will have to decide. Putting all this together using a Button click event to signal when to filter the grid may look something like below
private DataTable gridTable;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
gridTable = GetTable();
FillTable(gridTable);
dgv1.DataSource = gridTable;
textBox1.Text = "18";
}
private void FillTable(DataTable dt) {
dt.Rows.Add("0-18");
dt.Rows.Add("19-100");
dt.Rows.Add("0-100");
dt.Rows.Add("17-80");
dt.Rows.Add("18-80");
}
private DataTable GetTable() {
DataTable dt = new DataTable();
dt.Columns.Add("AgeRange", typeof(string));
return dt;
}
private void button1_Click(object sender, EventArgs e) {
if (textBox1.Text == "") {
dgv1.DataSource = gridTable;
return;
}
dgv1.DataSource = GetFilterTable();
}
Hacky Approach 2
The first approach works; however, I am guessing if there is a LOT of data and a LOT of filtering, this may become a performance issue. Therefore, in this approach, extra steps are taken in the beginning to take advantage of the DataTables RowFilter feature, as the posted code is doing. Obviously as stated previously, we will not use the “LIKE” comparator, instead the “<=” and “>=” operators are used.
In order to accomplish this, we MUST somehow turn the given string range “XX-XX” into two (2) ints. Then “add” these integers to the DataTable. Then it will be easy to filter the table using the RowFilter property and the less than and greater than operators. One problem is that it will require “extra” work on our part to set up the grid’s columns properly or these extra two columns of data will also display.
This can be done in the “designer” or manually in code. Without going into too much detail, it is useful to bear in mind that IF you assign a DataTable as a data source to the grid AND you set the grids AutoGenerateColumns property to false… THEN only the grid columns with DataPropertyName names that “match” one of the DataTable column names… will display. In this case, we only want the AgeRange column with the “XX-XX” strings to display, the other two new columns can remain hidden from the user. Setting up the grid column manually may look something like below, however you can do this in the designer. NOTE: the designer does not display an AutoGenerateColumns property, you have to do this in your code.
private void AddGridColumn() {
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.Name = "AgeRange";
col.DataPropertyName = "AgeRange";
col.HeaderText = "Age Range";
dgv1.Columns.Add(col);
}
The important point is that the DataPropertyName MUST match the target column name in the DataTable, otherwise the column will not display.
Next is the construction of the new DataTable. This method is given the original DataTable. A new DataTable is created with three (3) columns, AgeRange-string (displayed), StartRange-int and EndRange-int. The start and end columns will not be displayed. Once this new table is constructed, a foreach loop is started through all the rows in the original table. The string digits from the original tables row are “parsed” into actual numbers and added to the new DataTable along with the original “range” string. This method could look something like below. A helper method is further below to help split the age range string and return a number.
private DataTable GetSplitTable(DataTable sourceTable) {
DataTable dt = new DataTable();
dt.Columns.Add("AgeRange", typeof(string));
dt.Columns.Add("StartRange", typeof(int));
dt.Columns.Add("EndRange", typeof(int));
foreach (DataRow row in sourceTable.Rows) {
int startValue = GetIntValue(row.ItemArray[0].ToString(), 0);
int endValue = GetIntValue(row.ItemArray[0].ToString(), 1);
dt.Rows.Add(row.ItemArray[0], startValue, endValue);
}
return dt;
}
private int GetIntValue(string rangeString, int index) {
string[] splitArray = rangeString.Split('-');
int value = 0;
int.TryParse(splitArray[index], out value);
return value;
}
Putting all this together may look like below. Note, the button click event checks to see if the text box is empty, and if it is, will remove the current filter if one is applied.
private DataTable gridTable;
private DataTable splitTable;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
gridTable = GetTable();
FillTable(gridTable);
splitTable = GetSplitTable(gridTable);
AddGridColumn();
dgv1.AutoGenerateColumns = false;
dgv1.DataSource = splitTable;
textBox1.Text = "18";
}
private void FillTable(DataTable dt) {
dt.Rows.Add("0-18");
dt.Rows.Add("19-100");
dt.Rows.Add("0-100");
dt.Rows.Add("17-80");
dt.Rows.Add("15-75");
}
private DataTable GetTable() {
DataTable dt = new DataTable();
dt.Columns.Add("AgeRange", typeof(string));
return dt;
}
private void AddGridColumn() {
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.Name = "AgeRange";
col.DataPropertyName = "AgeRange";
col.HeaderText = "Age Range";
dgv1.Columns.Add(col);
}
private void button1_Click(object sender, EventArgs e) {
string filterString = "";
DataView dv;
if (textBox1.Text != "") {
filterString = string.Format("StartRange <= {0} AND EndRange >= {0}", textBox1.Text);
}
dv = new DataView(splitTable);
dv.RowFilter = filterString;
dgv1.DataSource = dv;
}
This Code:
("AgeRange LIKE '%{0}' OR AgeRange LIKE '{0}%'", textBoxFilter.Text)
is a redundant with two AgeRange LIKE
If you want to search like textBoxFilter.Text you can try
("AgeRange LIKE '%{0}%'", textBoxFilter.Text)
Or
StringBuilder rowFilter = new StringBuilder();
rowFilter.Append("AgeRange Like '%" + textBoxFilter.Text + "%'");
(dgv1.DataSource as DataTable).DefaultView.RowFilter = rowFilter.ToString();

How to Use Virtual Mode for large data in DataGridView

I am posting to see if there is a way to improve some legacy code. The code will populate a DataGridView with x amount of rows. Initially, the code worked fine as the populating data was of a small quantity. However, there has been an extreme increase in data and I am finding that the performance in populating the DataGridView to be very slow.
Basically, I know there are several considerations (Virtual Mode, for instance). However, the approach that I want to take is using an array or List (and then convert it to an array) and add the range of the row by calling Rows.AddRange(array). However, I am having trouble implementing it.
As it stands, this is what code exists:
if (value !=0)
{
int row = 0;
dataGridView1.AddRow();
dataGridView1.Rows[row].Cells[0] = "Test";
dataGridView1.Rows[row].Cells[1] = 9;
dataGridView1.Rows[row].Cells[2] = "Test Two";
dataGridView1.Rows[row].Cells[3] = "Test Three";
row++;
}
if (valueTwo !=0)
{
dataGridView1.AddRow();
dataGridView1.Rows[row].Cells[0] = "Test";
dataGridView1.Rows[row].Cells[1] = 9;
dataGridView1.Rows[row].Cells[2] = "Test Two";
dataGridView1.Rows[row].Cells[3] = "Test Three";
row++;
}
So, this is not efficient at all, of course. I know .AddRow() is a taxing method in itself and individually adding rows, one-by-one is not great.
I have tried something like:
object[] data = {"Test", 9, "Test Two", "Test Three"};
List<DataGridViewRow> list = new List<DataGridViewRow>();
for (int i = 0; i < data.Length; i++)
{
DataGridViewRow row = new DataGridViewRow();
row.SetValues(data[i]);
list.Add(row);
}
dataGridViewRow1.Rows.AddRange(list.ToArray());
However, doing this gets me a NullPointerException on the SetValues line.
I understand that the best way of doing this is either make a DataTable or use Virtual Mode but I want to try out using this method of adding the range and passing in a container for the data, rather than adding a row.
I hope I am clear with my explanation. Let me know if I need to further explain.
EDIT: I think using Virtual Mode is the best way to go. I am not sure how to really do it, though. I checked MSN's tutorial but I was slightly confused by it. If I were to implement Virtual Mode for 100,000 rows, how would I go about doing it. Nothing really fancy, just displaying a total of 10,000 rows.
i can prefer DataTable is the correct approach,
but still if you want to add data to your gridView dynamically,
first you need to add columns then rows.
private void Form5_Load(object sender, EventArgs e)
{
var lstTemp = new List<test>();
for (int i = 0; i < 10; i++)
lstTemp.Add(new test() { Name = "Test", No = i, Desc = "Desc " + i, Desc1 = "Desc1 " + i });
dataGridView1.Columns.Add("Name", "Name");
dataGridView1.Columns.Add("No", "Number");
dataGridView1.Columns.Add("Desc", "Description1");
dataGridView1.Columns.Add("Desc1", "Description2");
foreach (var temp in lstTemp)
{
DataGridViewRow row = (DataGridViewRow) dataGridView1.Rows[0].Clone();
row.Cells[0].Value = temp.Name;
row.Cells[1].Value = temp.No;
row.Cells[2].Value = temp.Desc;
row.Cells[3].Value = temp.Desc1;
dataGridView1.Rows.Add(row);
}
}
public class test
{
public string Name { get; set; }
public int No { get; set; }
public string Desc { get; set; }
public string Desc1 { get; set; }
}
this might help you,
for your case you need to add columns before rows,
object[] data = { "Test", 9, "Test Two", "Test Three" };
dataGridView1.Columns.Add("Name", "Name");
dataGridView1.Columns.Add("No", "Number");
dataGridView1.Columns.Add("Desc", "Description1");
dataGridView1.Columns.Add("Desc1", "Description2");
for (int i = 0; i < 10; i++)
dataGridView1.Rows.Add(data);
Try to use a BindingList that you populate with your data, you can have a class to map the propreties or use a dynamic one. You have to frist create the cols so you can Bind de data: here´s one example:
DataGridViewCell cell = new DataGridViewTextBoxCell();
DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()
{
CellTemplate = cell,
Name = "Value1",
HeaderText = "Value 1",
DataPropertyName = "Col1"
};
DataGridViewCell cell2 = new DataGridViewTextBoxCell();
DataGridViewTextBoxColumn colFileName2 = new DataGridViewTextBoxColumn()
{
CellTemplate = cell2,
Name = "Value2",
HeaderText = "Value 2",
DataPropertyName = "Col2"
};
dataGridView1.Columns.Add(colFileName);
dataGridView1.Columns.Add(colFileName2);
List<DataPopulate> list = new List<DataPopulate>();
list.Add(new DataPopulate() { Col1 = "tes1", Col2 = "teste2"});
list.Add(new DataPopulate() { Col1 = "tes1", Col2 = "teste2" });
list.Add(new DataPopulate() { Col1 = "tes1", Col2 = "teste2" });
var dataPopulateList = new BindingList<DataPopulate>(list);
dataGridView1.DataSource = dataPopulateList;

Getting the contents from wpf datagrid control into a data table

I'm trying to make an app for work where I enter some data into some controls (start date and end date wage week ) and then the user picks a csv extract from our wage program. The app then merges the data from the controls and the csv file into a datatable which is then set as the datacontxct of the wpf datagrid view.
this.dgCSVData.DataContext = oDS.Tables[0].DefaultView;
So as I under stand it the datagrid is now bound (that is a question not a statement) Here is a screen shot
The datagrid is in the "shape" of the datatable in the sql database I want to append the data to. However the datatable was created in a private event handler CSV_Load_Click, code block below.
What I had hoped to do is set another button event handler up call "Upload Data" and pass the datatable (oDS.Tables[0].DefaultView) to the DAL layer to be read and appended to sql database table, the problem is how do I make the datatable available, should I have created a class to match my data row and then created a public list of the rows?
private void CSV_Load_Click(object sender, RoutedEventArgs e)
{
//Turn on upload button
btUpload.IsEnabled = true;
//To load and display CSV data
//string filename = txFilePath.Text;
string delimStr = ",,";
char[] delimiter = delimStr.ToCharArray();
string strFilePath = txFilePath.Text;
DataSet oDS = new DataSet();
string strFields = null;
DataTable oTable = new DataTable();
DataRow oRows = null;
Int32 intCounter = 0;
oDS.Tables.Add("Property");
StreamReader oSR = new StreamReader(strFilePath);
//Go to the top of the file
oSR.BaseStream.Seek(0, SeekOrigin.Begin);
string File = fileTest;
//System.Windows.MessageBox.Show(File.ToString());
//Add in the Header Columns check if headers in first row
if (rbYes.IsChecked==true)
// action for headers in row 1
{
foreach (string strFields_loopVariable in oSR.ReadLine().Split(delimiter))
{
strFields = strFields_loopVariable;
oDS.Tables[0].Columns.Add(strFields);
}
}
else
{
if (File==#"CHHOURS.CSV")
{
string TitleHeaders = "Wage_Year,Wage_Start_Date,Wage_End_Date,Tax Week,Wk_No,Clock,Surname,Initial,Dept,Dept_Hours,Other_Hours,Total_Hours,OT_Hours,";
foreach (string strFields_loopVariable in TitleHeaders.Split(delimiter))
{
strFields = strFields_loopVariable;
oDS.Tables[0].Columns.Add(strFields);
}
}
else
{
Int32 i = 0;
foreach (string strFields_loopVariable in oSR.ReadLine().Split(delimiter))
{
string ColumLetter = "abcdefghijklmnopqrstuvwxyz";
strFields = ColumLetter[i].ToString();
oDS.Tables[0].Columns.Add(strFields);
i += 1;
}
}
}
//String request = oSR.ReadToEnd();
//Now add in the Rows
oTable = oDS.Tables[0];
while ((oSR.Peek() > -1))
{
oRows = oTable.NewRow();
if (File == #"CHHOURS.CSV")
{
oRows[intCounter] = cbWageYear.Text;
intCounter = intCounter + 1;
oRows[intCounter] = dpStartDate.SelectedDate;
intCounter = intCounter + 1;
oRows[intCounter] = dpEndDate.SelectedDate;
intCounter = intCounter + 1;
oRows[intCounter] = cBTaxWeek.SelectedIndex;
intCounter = intCounter + 1;
}
foreach (string strFields_loopVariable in oSR.ReadLine().Split(delimiter))
{
strFields = Convert.ToString(strFields_loopVariable);
if (intCounter < 20)
{
oRows[intCounter] = strFields;
intCounter = intCounter + 1;
}
else
{
}
}
intCounter = 0;
oTable.Rows.Add(oRows);
}
this.dgCSVData.DataContext = oDS.Tables[0].DefaultView;
}
Ok so I woke up this morning with an idea and It worked .wow!
All I did was declare my dataset as public before the constructor of my class. Now there might be a "better" way but that worked for me. Ii have been able to call my update method from my DAL and create a datareader, so now just the update to sql to do, then bug fixing.
I am almost happy :)
here is the code
public partial class MainWindow : Window
{
public List<TaxWeek> LTaxWeeks { get; set; }
public TaxWeek SelectedTaxWeek { get; set; }
**public DataSet oDS = new DataSet();**
public MainWindow()
{
InitializeComponent();
}

Categories

Resources