以下是我正在做什么的一些背景...C#ASP.NET - 使用代码编写的SQL查询语句数量减少
我正在编写一个C#web应用程序。在主页上,我有一个包含大约25个单独的Dropdownlists的数据输入表单。我创建了一个名为options的表,它非常简单(ID,Category,Option)。我创建的每个选项都进行了分类,因此我的查询将只包含与查找类别相匹配的选项。每个类别都与我需要填写的25个下拉列表中的一个匹配。
所以我能够得到一些这些填充形式和他们的工作很好。我担心这个代码的重写(DDlist名称和类别名称的细微变化)会导致代码长得多。有没有一种方法可以创建它自己的类,并将参数传递给类,以便它仅从正确的类别返回数据并填充正确的下拉列表?以下是我迄今为止的2个DD字段的示例代码。该DDStationList和DDReqeustType是我创造的25个Dropdownlists的2名:从我的配置文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
namespace TEST
{
public partial class _Default : Page
{
//Main connection string
string SqlConn = ConfigurationManager.AppSettings["SqlConn"];
string qryRequestType = ConfigurationManager.AppSettings["qryRequestTypes"];
string qryStationNumbers = ConfigurationManager.AppSettings["qryStationNumbers"];
protected void Page_Load(object sender, EventArgs e)
{}
protected void BtnAddNew_Click(object sender, EventArgs e)
{
//GET Request Types
DataTable RequestTypes = new DataTable();
SqlConnection Conn = new SqlConnection(SqlConn);
{
SqlDataAdapter adapter = new SqlDataAdapter(qryRequestType, Conn);
adapter.Fill(RequestTypes);
DDRequestType.DataSource = RequestTypes;
DDRequestType.DataTextField = "Option";
DDRequestType.DataValueField = "Option";
DDRequestType.DataBind();
}
// Get Stations
DataTable Stations = new DataTable();
SqlConnection Conn = new SqlConnection(SqlConn);
{
SqlDataAdapter adapter = new SqlDataAdapter(qryStationNumbers, Conn);
adapter.Fill(Stations);
DDStationList.DataSource = Stations;
DDStationList.DataTextField = "Option";
DDStationList.DataValueField = "Option";
DDStationList.DataBind();
}
}
protected void BtnSubmit_Click(object sender, EventArgs e)
{
//More stuff to do here for submit code
}
}
}
例子查询对应于上面的代码:
SELECT [Option] FROM Table WHERE Category = 'RequestType';
SELECT [Option] FROM Table WHERE Category = 'Station';
那么,有没有可能,我可以创建一个类,我可以通过该选项的类别到运行查询像这样:
SELECT [Option] FROM Table WHERE Category = @Category;
...然后填入正确的下拉列表(需要这样做25次)?
如果我不是清楚我的问题,我会很乐意进一步解释。
至于,'有没有一种方法我可以创建一个类它自己的和参数传递给类,所以它只返回我的数据来自正确的类别并填充正确的下拉列表,您可能更适合向当前班级添加功能。 –
您能给我一个例子吗? – Joe