17071

C# Loading words from Database and adding them to a list of type “Choices”?

I have a built a system which loads words from a database table but I need to add those words to a list of type "Choices" (the type that is needed for Grammar Building).

This is my code for requesting words to be retrieved from the database:

List<string> newWords = new List<string>(); newWords = LexicalOperations.WordLibrary().ToList(); Choices dbList = new Choices(); //Adding them to a Choice List if (newWords.Count != 0) { foreach (string word in newWords) { dbList.Add(word.ToString()); } } else dbList.Add("Default");

This is my code of retrieving data from the table:

public class LexicalOperations { public static List<string> WordLibrary() { List<string> WordLibrary = new List<string>(); string conString = "Data Source=.;Initial Catalog=QABase;Integrated Security=True"; using (SqlConnection connection = new SqlConnection(conString)) { connection.Open(); string sqlIns = "select WordList from NewWords"; SqlCommand cmd = new SqlCommand(sqlIns, connection); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); sda.Fill(ds); foreach (DataRow dr in ds.Tables[0].Rows) { WordLibrary.Add(dr[0].ToString()); } } return WordLibrary; } }

HOWEVER, This throws an exception: <strong>System.FormatException</strong> which also states the message:

FormatException was unhandled

Double-quoted string not valid.

This error is thrown when I build the choices list in a Speech Grammar Builder:

GrammarBuilder graBui = new GrammarBuilder(dbList); Grammar Gra = new Grammar(graBui);

What am I doing wrong? What should be done in order to properly retrieve words from the database and add them to a Choice list?

Answer1:

The problem seems to be that your Grammar class cannot handle strings with double quotes. So, the simplest way to remove the problem is to remove the double quotes by your input.

public class LexicalOperations { public static List<string> WordLibrary() { List<string> WordLibrary = new List<string>(); string conString = "Data Source=.;Initial Catalog=QABase;Integrated Security=True"; string sqlIns = "select WordList from NewWords"; using (SqlConnection connection = new SqlConnection(conString)) using (SqlCommand cmd = new SqlCommand(sqlIns, connection)) { connection.Open(); using(SqlDataReader reader = cmd.ExecuteReader()) { while(reader.Read()) { string noQuotes = reader.GetString(0).Replace("\"", ""); WordLibrary.Add(noQuotes); // In alternative you could also opt to not add a string with double quotes // string noQuotes = reader.GetString(0); // if(noQuotes.IndexOf("\"") < 0) // WordLibrary.Add(noQuotes); } } } return WordLibrary; } }

Notice that I have also removed the SqlDataAdapter and the filling of a DataSet. In this context is useless and clearly hinders the performance because you are executing two loops. The first one is executed by the Framework to fill the DataSet, the second by your code to add the words to the List<string> variable

Recommend

  • selecting a certain column value from looping in ienumerable
  • How to deploy C# windows application (setup file) with database and how to manage connection string
  • Classic ASP global.asa SQL Server 2008 connection string
  • VBA ADO Excel 2010
  • Elmah not logging 404 (missing files / images)
  • Login failed for user ''
  • Can I disable IE compatibility mode only for content within a ?
  • SQL Server 2005, Caches and all that jazz
  • How can I create a plugin mechanism that calls functions only when the plugin is available?
  • The symbol you provided is not a function
  • How to handle empty space in url when downloading image from web?
  • Insert audio album in Android MediaStore
  • Smack 4.1.0 android Roster not displaying
  • Send data from edittext to listview
  • Retrofit SocketTimeoutException (and/or http 500 error) on http-POST
  • Unable to connect to OnVif enabled camera using C#
  • SqlCommand back up Database
  • Extract All Possible Paths from Expression-Tree and evaluate them to hold TRUE
  • Retrieve IP address of device
  • blade.php method outputting it's result to the form
  • xcode don't localize specific strings
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • Getting last autonumber in access
  • Counter field in MS Access, how to generate?
  • Volley JsonObjectRequest send headers in GET Request
  • Modifying destination and filename of gulp-svg-sprite
  • Javascript convert timezone issue
  • Javascript + PHP Encryption with pidCrypt
  • Websockets service method fails during R startup
  • GridView Sorting works once only
  • Proper way to use connect-multiparty with express.js?
  • Why can't I rebase on to an ancestor of source changesets if on a different branch?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • embed rChart in Markdown
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • apache spark aggregate function using min value
  • Checking variable from a different class in C#
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app