70803

Getting an InvalidCastException was Unhandled

Question:

This is a take on some experimental code that @Tim Schmelter pointed me in the correct direction towards earlier this afternoon. The majority of it is almost exactly the same as what worked earler, but it is throwing a invalidCastException on the last line or second last line, depending whichever i try. I cannot see why this is.

Boolean test = false; string filePathStudent = System.IO.Path.GetFullPath("StudentInfo.txt"); DataTable studentDataTable = new DataTable(); studentDataTable.Columns.Add("Id", typeof(int)); studentDataTable.Columns.Add("StudentID"); studentDataTable.Columns.Add("FirstName"); studentDataTable.Columns.Add("LastName"); studentDataTable.Columns.Add("StreetAdd"); studentDataTable.Columns.Add("City"); studentDataTable.Columns.Add("State"); studentDataTable.Columns.Add("Zip"); studentDataTable.Columns.Add("Choice1"); studentDataTable.Columns.Add("CreditHrs1"); studentDataTable.Columns.Add("Choice2"); studentDataTable.Columns.Add("CreditHrs2"); studentDataTable.Columns.Add("Choice3"); studentDataTable.Columns.Add("CreditHrs3"); studentDataTable.Columns.Add("Choice4"); studentDataTable.Columns.Add("CreditHrs4"); studentDataTable.Columns.Add("Choice5"); studentDataTable.Columns.Add("CreditHrs5"); studentDataTable.Columns.Add("Choice6"); studentDataTable.Columns.Add("CreditHrs6"); foreach (string line in File.ReadLines(filePathStudent)) { DataRow row = studentDataTable.Rows.Add(); string[] fields = line.Split(new[] { (char)9 }); int id; if (fields.Length == 19 && int.TryParse(fields[0], out id)) { row.SetField("Id", id); row.SetField("StudentID", fields[1]); row.SetField("FirstName", fields[2]); row.SetField("LastName", fields[3]); row.SetField("StreetAdd", fields[4]); row.SetField("City", fields[5]); row.SetField("State", fields[6]); row.SetField("Zip", fields[7]); row.SetField("Choice1", fields[8]); row.SetField("CreditHrs1", fields[9]); row.SetField("Choice2", fields[10]); row.SetField("CreditHrs2", fields[11]); row.SetField("Choice3", fields[12]); row.SetField("CreditHrs3", fields[13]); row.SetField("Choice4", fields[14]); row.SetField("CreditHrs4", fields[15]); row.SetField("Choice5", fields[16]); row.SetField("CreditHrs5", fields[17]); row.SetField("Choice6", fields[18]); row.SetField("CreditHrs6", fields[19]); } } using (StreamReader reader = new StreamReader(filePathStudent)) { String line1 = reader.ReadLine(); if (line1 == null) maxIDStdTable = 0; else test = true; reader.Dispose(); reader.Close(); } if(test) int maxIDStdTable = studentDataTable.AsEnumerable().Max(r => r.Field<int>("Id")); //int maxIDStdTable = (int)studentDataTable.Compute("Max(Id)", "");

Answer1:

You have made two mistakes :<br /> 1) You have create new DataRow with <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.newrow.aspx" rel="nofollow">DataTable.NewRow()</a><br /> 2) Sfter setting DataRow you have to add it to the DataTable with DataTable.Rows.Add(youDataRow). <br /> Update your code as and try:

foreach (string line in File.ReadLines(filePathStudent)) { DataRow row = studentDataTable.NewRow(); string[] fields = line.Split(new[] { (char)9 }); int id; if (fields.Length == 19 && int.TryParse(fields[0], out id)) { row["Id"]= id; row["StudentID"]= fields[1]; row["FirstName"]= fields[2]; row[LastName"]= fields[3]; row["StreetAdd"]= fields[4]; row["City"]=fields[5]; row["State"]= fields[6]; row["Zip"]=fields[7]; row["Choice1"]= fields[8]; row["CreditHrs1"]= fields[9]; row["Choice2"]= fields[10]; row["CreditHrs2"]= fields[11]; row[("Choice3"]= fields[12]; row["CreditHrs3"]=, fields[13]; row["Choice4"]= fields[14]; row["CreditHrs4"]= fields[15]; row["Choice5"]= fields[16]; row["CreditHrs5"]= fields[17]; row["Choice6"]= fields[18]; row["CreditHrs6"] =fields[19]; } studentDataTable.Rows.Add(row); }

Answer2:

It might not be the best solution, but it works.

string filePathStudent = System.IO.Path.GetFullPath("StudentInfo.txt"); DataTable studentDataTable = new DataTable(); studentDataTable.Columns.Add("Id", typeof(Int32)); studentDataTable.Columns.Add("StudentID"); studentDataTable.Columns.Add("FirstName"); studentDataTable.Columns.Add("LastName"); studentDataTable.Columns.Add("StreetAdd"); studentDataTable.Columns.Add("City"); studentDataTable.Columns.Add("State"); studentDataTable.Columns.Add("Zip"); studentDataTable.Columns.Add("Choice1"); studentDataTable.Columns.Add("CreditHrs1"); studentDataTable.Columns.Add("Choice2"); studentDataTable.Columns.Add("CreditHrs2"); studentDataTable.Columns.Add("Choice3"); studentDataTable.Columns.Add("CreditHrs3"); studentDataTable.Columns.Add("Choice4"); studentDataTable.Columns.Add("CreditHrs4"); studentDataTable.Columns.Add("Choice5"); studentDataTable.Columns.Add("CreditHrs5"); studentDataTable.Columns.Add("Choice6"); studentDataTable.Columns.Add("CreditHrs6"); // Read in a file line-by-line, and store it var txtFileLine = File.ReadAllLines(filePathStudent).ToList(); //Reads line splits data to colums at tab (ASCII value 9) txtFileLine.ForEach(line => studentDataTable.Rows.Add(line.Split((char)9))); List<int> rowsForColumn1 = studentDataTable.AsEnumerable().Select(x => x.Field<int>(0)).ToList(); //Tests for empty Datatable foreach (DataRow row in studentDataTable.Rows) { if (row.IsNull("Id")) break; else //get max value from "Id" row. maxIDStdTable = rowsForColumn1.Max(); } }

Recommend

  • Undefined index html
  • what wrong with this paper and rock mini game?
  • Angular JS post object to Jersey is null
  • JPA - getting distinct value from one column
  • php regex remove digits
  • Add delivery info to query in SAP Crystal Reports
  • Update a record where _id = :id with Mongoose
  • Using : for multiple slicing in list or numpy array
  • VB.NET: How do I use coalesce with db column values and nullable types? Or is there a better solutio
  • ValueError: Found arrays with inconsistent numbers of samples
  • How to remove comma or any characters from Python dataframe column name
  • LINQ to Entities does not recognize the method 'System.Collections.Generic.Dictionary`2[System.
  • Skip Characters in Oracle TO_DATE function
  • Table striping rows in CSS Grid
  • Error in GGally: Error in unit(tic_pos.c, “mm”) : 'x' and 'units' must have leng
  • Using an array for autofilter criteria
  • Eloquent Relationship on Partial Match
  • HighCharts - Show tooltip on column where value is 0 or null
  • Strong vs Weak entities MYSQL
  • Can I update/select from a table in one query?
  • Bound DataGridViewCheckBoxColumn not updating binding source
  • XMLBeans Duplicate Class and Class Not Found Errors
  • How Get arguments value using inline assembly in C without Glibc?
  • WPF version of .ScaleControl?
  • Primefaces :radioButton inside a ui:repeat
  • How to make R's read_csv2() recognise the text characters properly
  • R convert summary result (statistics with all dataframe columns) into dataframe
  • Implementation of State Monad
  • Breaking out column by groups in Pandas
  • Unable to get column index with table.getColumn method using custom table Model
  • How to add git credentials to the build so it would be able to be used within a shell code?
  • How do I pass the string value parameter of the selected list item from an auto-populated dropdown l
  • Disable Enter in editText android
  • Dynamically accessing properties of knockoutjs observable array
  • json Serialization in asp
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Java static initializers and reflection
  • How to stop GridView from loading again when I press back button?
  • Android Google Maps API OnLocationChanged only called once
  • UserPrincipal.Current returns apppool on IIS