我正在尝试弄清楚如何访问和存储下拉列表中的选择,以便在 mainSQL 类的 SELECT 命令中使用。
具体细节如下。
DropDownList(位于名为 Page.aspx 的页面上):
<asp:DropDownList
ID="selectInfo1"
runat="server"
AutoPostBack="True"
DataTextField="Info1"
DataValueField="Info1Key"
DataSourceID="SqlDB" >
</asp:DropDownList>
我尝试访问 DDL 的函数(在单独的类文件中):
public List<ListInfo> getList()
{
List<ListInfo> sList = new List<ListInfo>();
ListInfo objList = null;
//This is where I need to declare a variable called Info1Key and set it to the value of the ddl!
string queryString = "SELECT [UniqueID], [Date], [Info1], [Info2], [Info3] FROM [ReportedSales] WHERE ([Info1] = ' " + Info1Key + "') ORDER BY [Date]";
using (SqlConnection connection = new SqlConnection(sqlConString))
{
using (SqlCommand command = new SqlCommand(queryString, connection))
{
command.Connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
objList = new ListInfo();
objList.ID = Convert.ToInt16(dataReader["UniqueID"]);
objList.Date = Convert.ToDateTime(dataReader["Date"]);
objList.Info1 = (dataReader["Info1"] as int?) ?? 0;
objList.Info2 = (dataReader["Info2"] as int?) ?? 0;
objList.Info3 = (dataReader["Info3"] as int?) ?? 0;
sList.Add(objList);
}
}
}
}
return sList;
}
这是唯一调用 getList 方法的函数(我很确定)--
private void FillListActivity()
{
List<ListInfo> objList = new List<ListInfo>();
objList = new mainSQL().getList();
ReportingGV.DataSource = objList;
ReportingGV.DataBind();
}
新问题 - 当我更改 DDL 时,GV 不再更改。
我可以解决这个问题的一种方法是更改 Page.aspx.cs 中的 Page_Load,如下所示:
原文:
protected void Page_Load(object sender, EventArgs e)
{
if(!isPostBack)
{
FillSalesActivity();
}
}
工作,但我会遇到问题吗?:
protected void Page_Load(object sender, EventArgs e)
{
FillSalesActivity();
}
最佳答案
您不希望外部类了解或关心任何有关 UI 元素(例如下拉列表)的信息。它们应该尽可能与 UI 无关。
相反,在这种情况下您想要做的是将值传递给函数。因此,您可以将函数签名更改为如下所示:
public List<ListInfo> getList(string Info1Key)
{
// The code is the same, just use the Info1Key parameter that's been passed to the function.
}
然后你可以像这样调用该函数:
private void FillSalesActivity()
{
List<SalesInfo> objSalesList = new List<SalesInfo>();
objSalesList = new mainSQL().getSalesList(selectInfo1.SelectedValue);
SalesReportingGV.DataSource = objSalesList;
SalesReportingGV.DataBind();
}
需要注意的几点:
- 您需要在页面上进行错误检查,以确保在调用该函数之前存在值
SelectedValue
。 - 您应该真正研究一下 SQL 注入(inject)漏洞,因为您的代码有一个。 永远绝对不要隐式信任来自客户端的值,即使它来自下拉列表并且您认为您可以控制这些值。你不知道。客户端可以发送他们想要的任何值(如果他们选择),并且该值可以包含 SQL 代码,您的函数将在拥有所需的所有权限的情况下对数据库愉快地运行这些代码。考虑使用“参数化查询”,或者更好的是 ORM 框架。像 Linq To Sql 这样的东西具有相当快的设置和较低的学习曲线,并且可以为您提供很多功能。
关于c# - 需要帮助通过类访问 DropDownList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14224402/