来自本地.mdf的数据未显示在listView

时间:2016-12-10 07:48:39

标签: c# sql-server database listview

当我运行我的代码时,我没有错误,代码似乎运行正常,但数据库中的数据没有显示在我的listView上。

这是我的设计师表单代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

namespace Cookbook
{
    public partial class frmMain : Form
    {
        SqlConnection connection;
        string connectionString;

        public frmMain()
        {
            InitializeComponent();
            connectionString = ConfigurationManager.ConnectionStrings["Cookbook.Properties.Settings.CookbookConnectionString"].ConnectionString;
        }

        public void frmMain_Load(object sender, EventArgs e)
        {
            PopulateRecipes();

        }

        public void PopulateRecipes()
        {
            using (connection = new SqlConnection(connectionString))
            using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Recipe", connection))
            {
                DataTable recipeTable = new DataTable();
                adapter.Fill(recipeTable);

                lstRecipes.DisplayMember = "Name";
                lstRecipes.ValueMember = "Id";
                lstRecipes.DataSource = recipeTable;
            }       
        }


        public void PopulateIngrediants()
        { 
            string query = "SELECT a.Name FROM Ingrediants a" +
            "INNER JOIN RecipeIngrediant b ON a.Id = b.IngrediantId" +
            "WHERE b.RecipeId = @RecipeId";

            using (connection = new SqlConnection(connectionString))
            using (SqlCommand command = new SqlCommand(query, connection))
            using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
            {
                command.Parameters.AddWithValue("@RecipeId", lstRecipes.SelectedValue);
                DataTable ingrediantsTable = new DataTable();
                adapter.Fill(ingrediantsTable);

                lstIngrediants.DisplayMember = "Name";
                lstIngrediants.ValueMember = "Id";
                lstIngrediants.DataSource = ingrediantsTable;
            }
        }

        public void lstRecipes_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulateIngrediants();
        }

        private void lblRecipes_Click(object sender, EventArgs e)
        {

        }

        private void frmMain_Load_1(object sender, EventArgs e)
        {

        }
    }
}

我的应用配置:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="Cookbook.Properties.Settings.CookbookConnectionString"
            connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Cookbook.mdf;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
</configuration>

这是我的代码结构,运行时视图为空白: enter image description here

注意:我正在使用Visual Studio Community 2015更新3,而且我是VS和C#的新手。

1 个答案:

答案 0 :(得分:0)

您的代码中存在多个问题。

  • 你忘记打开联系(并关闭它更好)
  • 连接时查询没有空格
  • 您忘记选择ID并在valuemember中使用id
  • 您使用命令参数并使用dataadapter而不使用链接

不是我的代码纠正了工作,但试试这个

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

namespace Cookbook
{
    public partial class frmMain : Form
    {
        SqlConnection connection;
        string connectionString;

        public frmMain()
        {
            InitializeComponent();
            connectionString = ConfigurationManager.ConnectionStrings["Cookbook.Properties.Settings.CookbookConnectionString"].ConnectionString;
        }

        public void frmMain_Load(object sender, EventArgs e)
        {
            PopulateRecipes();

        }

        public void PopulateRecipes()
        {
            using (connection = new SqlConnection(connectionString))
            using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Recipe", connection))
                {
                connection.Open(); //Open connexion 
                DataSet ds = new DataSet();
                adapter.Fill(ds );

                lstRecipes.DisplayMember = "Name";
                lstRecipes.ValueMember = "Id";
                lstRecipes.DataSource = ds.Tables[0];
                connection.Close(); //close connexion
                }


        }


        public void PopulateIngrediants()
        { 
            //Donc forget space in your query when you concat string for create query, add column a.id if you want use in valuemember
            string query = "SELECT a.Name, a.Id FROM Ingrediants a " +
            "INNER JOIN RecipeIngrediant b ON a.Id = b.IngrediantId " +
            "WHERE b.RecipeId = @RecipeId";

            //Remove your command
            using (connection = new SqlConnection(connectionString))
            using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
            {
                connection.Open() //open connexion
                adapter.SelectCommand.Parameters.AddWithValue("@RecipeId", lstRecipes.SelectedValue);//modify parameter of select command to dataadapter (verify selectvalue)
                DataSet ds = new DataSet();
                adapter.Fill(ds);

                lstIngrediants.DisplayMember = "Name";
                lstIngrediants.ValueMember = "Id";
                lstIngrediants.DataSource = ds.Tables[0];
                connection.Close() //close connexion
            }
        }

        public void lstRecipes_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulateIngrediants();
        }

        private void lblRecipes_Click(object sender, EventArgs e)
        {

        }

        private void frmMain_Load_1(object sender, EventArgs e)
        {

        }
    }
}