2014-10-03 83 views
2

我建立了一个系统,可以从数据库表中加载单词,但我需要将这些单词添加到“选择”类型(语法构建所需的类型)的列表中。C#从数据库中加载单词并将它们添加到“选择”类型的列表中?

这是从数据库中检索我的请求的话代码:

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

这是我从表中检索数据的代码:

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

然而,这将引发异常: System.FormatException其中还指出消息:

Fo rmatException是未处理的

双引号字符串无效。

,当我建立一个语音语法生成器的选择列表此错误是抛出:

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

我在做什么错?为了从数据库中正确检索单词并将它们添加到选项列表中应该做些什么?

+0

哪一行会引发错误? – DGibbs 2014-10-03 15:15:33

+2

*“双引号字符串无效”*听起来像是由dbList.Add()所做的任何事情引发的自定义异常? - 错误在哪里,当前字符串是什么样的? – 2014-10-03 15:15:58

+0

与问题无关,但前两行可写为'List newWords = LexicalOperations.WordLibrary();' – Steve 2014-10-03 15:17:54

回答

2

问题似乎是你的语法类不能用双引号处理字符串。
因此,解决问题的最简单方法是通过输入删除双引号。

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

注意,我也有除去SqlDataAdapterDataSet的填充。在这种情况下是无用的,并且明显阻碍了性能,因为您正在执行两个循环。第一个由框架执行以填充DataSet,第二个由您的代码添加单词到List<string>变量

相关问题