【问题标题】:C# Using Multiple Database Results with Listboxes that (when item is selected) Display Info in TextboxesC# Using Multiple Database Results with Listboxes that (when item is selected) Display Info in Textboxes
【发布时间】:2011-07-12 14:24:28
【问题描述】:

我正在使用数据库编写一本烹饪书。因为我还是个新手,所以我一直在使用教程来构建我的项目。

我之前问过如何使用按钮搜索数据库,帮助太快了,我得再问一个问题。

问题来了:

我的表单允许用户查找具有特定成分的食谱。它允许他们在文本框中键入一种成分,并且该按钮在列表框中显示所有结果(食谱的名称)。由于此处的帮助,该部分已成功编码。但是,一旦填充了列表框,我希望用户能够从列表框中选择一个食谱,并且列表框旁边的文本框会填充特定食谱的数据信息(例如成分、方向和其他厘米)。

填充列表框的配方取决于用户,所以如果没有一些严肃的逻辑,我真的无法编写代码,对吧?

这是我整个表单的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Collections;


namespace Cookbook
{
    public partial class BrowseIngredients : Form
    {
        public BrowseIngredients()
        {
            InitializeComponent();
        }

        SqlConnection con;
        SqlDataAdapter dataAdapt;
        DataSet dataRecipe;
        int MaxRows = 0;
        int inc = 0;


        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Exit Cook Book?", "Exit?", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                Application.Exit();
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            BrowseRecipes goBack = new BrowseRecipes();

            Close();
            goBack.Show();
        }

        private void howToSearchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("To look for recipes with ingredients you have, simply type in the first ingredient you have to cook. \r\n To narrow your search, add another ingredient you'd like to search for in the recipe results.", "Search by Ingredients");
        }


        private void BrowseIngredients_Load(object sender, EventArgs e)
        {

            con = new SqlConnection();
            con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Documents and Settings\\Cady Wong\\My Documents\\Visual Studio 2010\\Projects\\Cookbook\\Cookbook\\Recipes.mdf;Integrated Security=True;User Instance=True";
            dataRecipe = new DataSet();

            con.Open();

           string sql = "SELECT* From CookBookRecipes";
           dataAdapt = new SqlDataAdapter(sql, con);
           dataAdapt.Fill(dataRecipe, "CookBookRecipes");
           NavigateRecords();
           MaxRows = dataRecipe.Tables["CookBookRecipes"].Rows.Count;

            con.Close();

        }

        private void NavigateRecords()
        {
            DataRow dRow = dataRecipe.Tables["CookBookRecipes"].Rows[inc];

        }


//This is the search and populate listbox code //


        private void btnSearch_Click(object sender, EventArgs e)
        {


            if (tbSearch.TextLength >= 1)
           {
                //MessageBox.Show("This will work when you put in a word!");

               listBox1.Items.Clear();

                string searchOut = tbSearch.Text;
                int result = 0;

                DataRow[] returnRows;

                returnRows = dataRecipe.Tables["CookBookRecipes"].Select("Recipe_Ingredients LIKE '*" + searchOut + "*'");


                result = returnRows.Length;

//This allows mutiple results to be seen one line after another //

                if (result > 0)
                {
                    string temp ="";
                    DataRow rowBack;
                    for (int index = 0; index < returnRows.Count(); index++ )
                    {
                        rowBack = returnRows[index];
                        listBox1.Items.Add(rowBack[0].ToString());
                        temp += rowBack[0].ToString();
                        temp += "\n";
                    }

                }
                else
                {
                    MessageBox.Show("No record");
                }

           }

           else
            {
               MessageBox.Show("Please enter an ingredient to search for!", "Search");
           }
        }

    }
}

如果您需要更多信息,请告诉我!

提前谢谢你!

【问题讨论】:

  • 那么当用户点击一个列表框项目时,你需要进行另一个数据库调用吗?像select * from table where recipe='quiche' 或类似的东西?
  • @Nick:我想,因为所有数据都在数据库中。列表框将由用户填充,因此我需要一些计算机逻辑来确定选择了哪个菜谱,以任何排序或顺序,以及如何获取该菜谱并提供其其余详细信息。这有意义吗?

标签: c# .net database logic


【解决方案1】:

好吧,我还没有真正提供答案 - 更糟糕的是,一些技巧希望能推动你前进,不仅仅是在这个项目上,而是作为一个程序员。

在我继续之前,稍微补充一下,标签“多重”和“逻辑”是您问题的一个特殊选择

关于 BrowseIngredients_Load:

这里使用了实现IDisposable 接口的SqlConnection。最佳实践(强烈推荐)是在处理实现 IDispoable 的对象时始终使用Using Block Pattern(至少在可能的情况下)。

using (con = New SqlConnection(connectionString)){
    ' use the connection within these bracers
}
' because you used this pattern, the object is disposed correctly, memory deallocated, etc

下一点建议是看一下 Linq to SQL(简称 L2S)。 L2S 是Object-Relational Mapper。听起来很复杂,但基本上意味着它负责将您的数据库对象(表、视图等)映射到您的域模型(类、结构等)。可能再次听起来有点复杂,但相信我,看看这些简单的教程,你会喜欢的:

CodeProject Article including Source Code

Part 1 of Scott Gu's Blog/Tutorials

Good ol' MSDN Introduction to L2S

注意:有很多可用的 ORM,Microsoft 本身也提供实体框架,但 L2S 应该易于学习,并为您提供足够的知识,以便在未来对 ORM 替代方案做出明智的选择 p>

如果您使用 L2S(一旦您使用了几个小时,您会发现您会在代码中每次都使用过度编写 T-SQL)它解决了一个其他几个问题,例如引入 Linq 将为您处理的 SQL Injection

它也可以解决您的整体问题,或者几乎可以解决。使用 Linq to SQL,显示食谱数据会很简单,因为它们只是类的属性。

txtIngredients.Text = myAutoGeneratedLinqRecipe.Ingredients;

我希望这能帮助你上路,我相信其他人会给你代码来完成你的练习,而不需要引入新的代码模式和技术^^

编辑:使用块的快速示例,以便您了解:

Private void BrowseIngredients_Load(object sender, EventArgs e)
{
    string connStr = "Data Source=.....etc";
    using (con = New SqlConnection(connStr))
    {
        con.Open
        ' get your data here - if you were losing Linq, you wouldnt have to worry
        ' about connections or Sql at all ;-)
        con.Close
    } ' this ensures that the connection is disposed correctly, even if for example
      ' you throw an exception inside the block which isn't caught
}

【讨论】:

  • 非常感谢,我会看那些教程的。顺便说一句,我想不出我的问题存在的任何标签,所以这就是为什么其中一些有点奇怪。
  • 没问题@C Wong,我认为只使用前 3 个(C#、.net、数据库 - 足够详细地描述问题)就可以了。如果你能通过任何一个教程并且不知道你自己问题的答案,我会吃掉我的帽子=D
  • 关于 using '(con = New SqlConnection(connectionString)){ connection code }' 是否直接位于我的代码中的 'using system.Collections' 下方?
  • 好的,谢谢。我正试图解决这个问题。使用 Linq to Sql,我可以重写我的整个代码,而无需连接字符串或 dataAdapters 或 commandBuilders 或所有其他东西?
  • 当然。您有一个称为 DataModel 的东西,它几乎是(您的数据库的)图片。 L2S 为您创建您需要的所有课程。如果您查看这些教程,您将了解如何使用您的“DataContext”(您需要一个连接字符串,但在简单的环境中,linq 可以在后台为您保存它,因此您不必拥有它代码),这反过来将获取您需要填充列表视图或文本框等的对象。检查一下,如果您有任何问题,请告诉我们。祝你好运!
猜你喜欢
  • 2013-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-03
相关资源
最近更新 更多