当没有数据时,SqlDataReader无效尝试读取

时间:2017-04-30 11:57:39

标签: c# sql-server

我使用此代码将数据从SQL Server导出到文本文件。但我在行中收到此错误消息:

if door_num == ghost_door

之后

sw.WriteLine(read["Total"].ToString());

代码:

while(read.Read())

1 个答案:

答案 0 :(得分:0)

解决:我只是使用一个字符串来获取循环中的值,然后在阅读后使用它。

  String Total;

  using (StreamWriter sw = new StreamWriter(@"C:\fiscal.txt"))
            {
                while (read.Read())
                {
                    sw.Write("S/");
                    string tempString = (read["Name"].ToString());
                    if (tempString.Length > 20)
                        tempString = tempString.Substring(0, 20);
                    else
                    {
                        tempString = tempString.PadRight(20);
                        tempString = tempString.PadLeft(0);
                    }
                    sw.Write(tempString + "/");
                    String.Format("{0:0.000}", 0.5);
                    sw.Write("  ");
                    sw.Write(String.Format("{0:0.000}", double.Parse(read["Quantity"].ToString())).Replace(",", ".") + "/");
                    sw.Write("   ");
                    sw.Write(String.Format("{0:0.00}", double.Parse(read["Price"].ToString())).Replace(",", ".") + "/");
                    sw.Write("      99/");
                    sw.Write(" " + read["MainGroupItemCode"].ToString() + "/");
                    sw.WriteLine();
                    Total = ("CR/  " + String.Format("{0:0.00}", double.Parse(read["Total"].ToString())).Replace(",", "."));

                }
                sw.WriteLine(Total);
                sw.Close();
                read.Close();