【发布时间】:2016-10-06 20:47:06
【问题描述】:
这里有一些关于我正在做的事情的背景......
我正在编写一个 C# Web 应用程序。在主页上,我有一个数据输入表单,其中包含大约 25 个单独的下拉列表。我创建了一个名为 options 的表,它非常简单(ID、Category、Option)。我创建的每个选项都进行了分类,因此我的查询将仅包含与我正在查找的类别匹配的选项。每个类别都匹配我需要填充的 25 个下拉列表之一。
因此,我可以在表单上填充其中的一些,并且效果很好。我担心重写此代码(DDlist 名称和类别名称略有不同)会导致代码更长。有没有办法我可以创建一个自己的类并将参数传递给该类,以便它只返回来自正确类别的数据并填充正确的下拉列表?这是到目前为止我为 2 个 DD 字段提供的一些示例代码。 DDStationList 和 DDReqeustType 是我创建的 25 个下拉列表中的 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 次)?
如果我的问题不清楚,我很乐意进一步解释。
【问题讨论】:
-
关于
Is there a way I can create a class of it's own and pass parameters to the class so it only returns me data from the correct category and populates the correct Dropdownlist,您最好在当前类中添加一个函数。 -
你能给我一个例子吗?
标签: c# asp.net sql-server