[英]Using a variable from the code behind in a select query
I've got a couple drop down lists and I want to make the value of the first DDL determine what fills up the second DDL. 我有几个下拉列表,我想让第一个DDL的值确定是什么填充了第二个DDL。 I thought maybe I could use autopostback to set the variable to the selected value and then in the second datasource, put it in my select query, like so:
我以为也许可以使用autopostback将变量设置为选定的值,然后在第二个数据源中将其放入我的选择查询中,如下所示:
Markup: 标记:
Select a Category:<br />
<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True"
DataSourceID="AccessDataSource1" DataTextField="ORG_NAME" DataValueField="ID"
OnSelectedIndexChanged="PopulateDDLsections">
</asp:DropDownList>
<br />
Select an Organization:<br />
<asp:DropDownList ID="ddlOrg" runat="server"
DataSourceID="AccessDataSource2" DataTextField="SectionName"
DataValueField="ID" >
</asp:DropDownList>
<asp:AccessDataSource ID="AccessDataSource2" runat="server"
DataFile="~/App_Data/webvideos.mdb"
SelectCommand="SELECT * FROM [ORG_SECTIONS] WHERE OrgID = ' + <%= orgID %>'"></asp:AccessDataSource>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/webvideos.mdb"
SelectCommand="SELECT * FROM [ORGANIZATIONS]"></asp:AccessDataSource>
Code Behind: 背后的代码:
public partial class AddRecord : System.Web.UI.Page
{
int orgID = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void PopulateDDLsections(object sender, EventArgs e)
{
orgID = Convert.ToInt32(ddlOrg.SelectedValue.ToString());
}
}
At first, I got a datatype mismatch, so I changed it to this: 最初,我遇到了数据类型不匹配的情况,因此将其更改为:
protected void PopulateDDLsections(object sender, EventArgs e)
{
string orgID = ddlOrg.SelectedValue.ToString();
}
but still got a datatype mismatch error. 但仍然出现数据类型不匹配错误。 Is what I'm trying to do as simple as I'm trying to make it?
我想做的和做起来一样简单吗? Can I get this way to work?
我可以用这种方式工作吗?
Is it possible to use the where clause in the datasource item? 可以在数据源项中使用where子句吗?
Basic example: http://msdn.microsoft.com/en-us/library/vstudio/tw738475(v=vs.100).aspx 基本示例: http : //msdn.microsoft.com/en-us/library/vstudio/tw738475(v=vs.100).aspx
Why don't you set the AccessDataSource2.SelectCommand
within the PopulateDDLsections()
routine - in the code behind. 为什么不在
PopulateDDLsections()
例程中设置AccessDataSource2.SelectCommand
在后面的代码中。
Something like: 就像是:
protected void PopulateDDLsections(object sender, EventArgs e)
{
int orgID;
// Make sure we parse the selected value to an int.
if(Int32.TryParse(ddlOrg.SelectedValue, out orgID))
{
// Form the select statement from the orgID we just parsed.
String command = String.Format("SELECT * FROM [ORG_SECTIONS] WHERE OrgID = {0}", orgID);
// Assign the SelectCommand.
AccessDataSource2.SelectCommand = command;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.