C#连接SQL数据库无报错但无法显示数据问题求助
Hey there, let's break down why your data isn't showing up even though Visual Studio isn't throwing errors. Here are the most likely fixes and checks to run through:
1. Fix the SQL Query Syntax
Your query uses Table which is a reserved keyword in SQL. If your table name is actually Table, you need to wrap it in square brackets to avoid parsing issues:
SELECT * FROM [Table]
Also, remove the trailing space after Table in your query string—while not always breaking, it's cleaner to avoid.
2. Correct ListBox Binding Property
You're using SelectedValue = "Id" but that's not the right property for binding. SelectedValue sets the currently selected value, while SelectedValuePath tells the control which column from your data to use as the selected value source. Change that line to:
listbmi.SelectedValuePath = "Id";
3. Verify Data is Actually Being Fetched
Add debug output to confirm if your query is returning any rows. Insert this line right after adapter.Fill(tabelabmi);:
System.Diagnostics.Debug.WriteLine($"Number of rows loaded: {tabelabmi.Rows.Count}");
Check the Output window in Visual Studio—if the count is 0, either your database table is empty, or your connection string is pointing to the wrong database instance/file.
4. Validate Connection String
Double-check that your connection string is targeting the correct database. Add a debug print in your constructor to see the actual string being used:
public MainWindow() { InitializeComponent(); connectionString = ConfigurationManager.ConnectionStrings["projekt1.Properties.Settings.Database1ConnectionString"].ConnectionString; System.Diagnostics.Debug.WriteLine("Connection String: " + connectionString); }
Make sure the path (if using a local .mdf file) or server name (if using SQL Server) is correct.
5. Confirm Load Event is Bound
Ensure your MainWindow_Load method is actually hooked up to the window's Loaded event. Check your XAML for this line:
<Window ... Loaded="MainWindow_Load">
If it's missing, the DisplayBMI() method never runs, so no data gets loaded.
Corrected DisplayBMI Method
Here's your method with the key fixes and debug checks added:
private void DisplayBMI() { // Declare connection inside using to ensure proper disposal using (SqlConnection connection = new SqlConnection(connectionString)) using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM [Table]", connection)) { DataTable tabelabmi = new DataTable(); adapter.Fill(tabelabmi); // Debug check for fetched rows System.Diagnostics.Debug.WriteLine($"Rows retrieved: {tabelabmi.Rows.Count}"); listbmi.DisplayMemberPath = "bmi"; listbmi.SelectedValuePath = "Id"; // Fixed property name listbmi.ItemsSource = tabelabmi.DefaultView; } }
Start with the first two fixes—they're the most common culprits here. If those don't work, use the debug outputs to narrow down whether the issue is with fetching data or binding it to the control.
内容的提问来源于stack exchange,提问作者weis_ss

