我正在做的事情很简单。我只需要连接到 SQL 数据库并从表中读取信息。我确信我错过了一些愚蠢的东西。我正在使用 C#、SQL Sever 和 WPF。显示的连接字符串是数据源构建器提供的连接字符串,因此我认为它是正确的。我测试了与它的连接,它是成功的。我附上了一些代码和图像来帮助你帮助我解决我的问题。
代码:
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=USSW7DEVWS16\\DEVELOPER;Initial Catalog=acrGIS;Integrated Security=True";
con.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM dbo.acrObjects", con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string Object = reader.GetString(0);
string Comment = reader.GetString(1);
string OStreet = reader.GetString(2);
string OCity = reader.GetString(3);
string OState = reader.GetString(4);
string OZip = reader.GetString(5);
string OSpec = reader.GetString(6);
arcObjects.Add(new acrObject() { Object_Num = Object, Comments = Comment, Street = OStreet, City = OCity, State = OState, Zip = OZip, Spec = OSpec });
}
foreach (acrObject objects in arcObjects)
{
MessageBox.Show(objects.ToString());
}
}
这是我的班级以及我的列表和连接定义:
class acrObject
{
public string Object_Num {get; set;}
public string Comments{get; set;}
public string Street {get; set;}
public string City {get; set;}
public string State{get; set;}
public string Zip {get; set;}
public string Spec {get; set;}
public override string ToString()
{
return string.Format("Object Number: {0}, Comments: {1}, Street: {2}, City: {3}, State: {4}, Zip: {5}, Spec: {6}", Object_Num, Comments, Street, City, State, Zip, Spec);
}
}
System.Data.SqlClient.SqlConnection con;
List<acrObject> arcObjects = new List<acrObject>();
异常的图像:
它发生在线:
while (reader.Read())
更奇怪的是有时不会抛出错误,它会跳过所有代码。所以它从来没有尝试显示我觉得很奇怪的消息框。谢谢您的帮助。如果您还有任何问题或希望我发布更多我的代码,请告诉我,我将很乐意。
显示断点和调用堆栈:
这是我执行 try/catch 时引发的异常: