C# 使用多个数据库结果与列表框(当选择项目时)在文本框中显示信息
我正在使用数据库编写一本烹饪书。自从我还是个新手以来,我一直在使用教程来构建我的项目。
我之前曾问过如何使用按钮搜索数据库,并且帮助如此之快,我不得不问另一个问题。
问题是:
我的表单允许用户查找具有某种成分的食谱。它允许他们在文本框中输入成分,按钮会在列表框中显示所有结果(食谱名称)。感谢此处的帮助,该部分已成功编码。不过,一旦填充了列表框,我希望用户能够从列表框中选择菜谱,并且列表框旁边的文本框填充特定菜谱的数据信息(例如成分、方向和附加信息)。评论)。
列表框中填充哪些食谱取决于用户,所以如果没有一些严肃的逻辑,我无法真正编写此代码,对吧?
这是我的整个表单的代码:
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");
}
}
}
}
如果您需要更多信息,请告诉我!
先感谢您!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我还没有真正提供答案——更多的是给你一些建议,希望这些建议能推动你前进,不仅是在这个项目上,而且作为一个程序员。
在我继续之前,需要注意一点,标签“multiple”和“logic”是您问题的特殊选择
关于 BrowseIngredients_Load:
这里您使用实现 IDisposable 接口。最佳实践(强烈推荐)是始终使用使用块模式< /a> 当使用实现 IDispoable 的对象时(至少在可能的情况下)。
下一个建议是看看 Linq to SQL(简称 L2S)。 L2S 是一个对象关系映射器。听起来很复杂,但基本上意味着它负责将数据库对象(表、视图等)映射到域模型(类、结构等)。可能听起来又有点复杂,但是相信我,看看这些简单的教程,您一定会喜欢它:
包含源代码的 CodeProject 文章
Scott Gu 博客/教程的第 1 部分
好ol' MSDN L2S简介
NB:有很多可用的ORM,微软本身也提供了实体框架,但是L2S应该很容易学习,并为你提供足够的知识来让你受教育未来 ORM 替代方案的选择
如果您选择 L2S(一旦您花了几个小时,您会发现您将在代码中使用 T-SQL 每隔< /strong> time)它解决了其他一些问题,例如引入 Linq 可以处理的 SQL 注入为你。
它还可以解决您的整体问题,或者几乎解决您的问题。使用 Linq to SQL,显示菜谱数据会很简单,因为它们只是类的属性。
我希望这有助于您上路,我相信其他人会给您代码来完成您的练习,而无需引入新的代码模式和技术^^
编辑:使用块的快速示例,以便您了解想法:
Ok, I haven't really provided the answer- more bane you with a few tips that hopefully will push you forward, not just on this project, but as a programmer in general.
On a slight side note before I continue, the tags "multiple" and "logic" are a perculiar choice for your question
Regarding BrowseIngredients_Load:
Here you use a SqlConnection which implements the IDisposable interface. The best practice (and it's very highly recommended) is to always use the Using Block Pattern when working with objects that implement IDispoable (at least where possible).
The next bit of advice would be to take a look at Linq to SQL (L2S for short). L2S is an Object-Relational Mapper. Sounds complicated but basically means it is responsible for mapping your database objects (Tables, Views, etc) to your Domain Model (Classes, Strucutres, etc). Probably again sounds a bit complicated, but trust me, check out these dead simple tutorials and you'll love it:
CodeProject Article including Source Code
Part 1 of Scott Gu's Blog/Tutorials
Good ol' MSDN Introduction to L2S
NB: There are many ORMs available, Microsoft itself also provides Entity Framework, but L2S should be easy to learn and arm you with enough knowledge to make educated choices towards ORM alternatives in the future
If you go with L2S (which once you've spent a couple hours with, you'll find you'll use over writing out T-SQL in your code every time) it solves a couple other issues, such as introducing SQL Injection which Linq would handle for you.
It would also solve your overall problem, or almost. With Linq to SQL, displaying the Recipes data would be simple because they would just be the properties of a class.
I hope that helps get you on your way, I'm sure somebody else will give you the code to complete your exercise without introducing new code patterns and technologies ^^
EDIT: A quick exmaple of the using block so you get the idea: