在我的应用程序中,我有2个删除列表,我填充了来自2个相关表的信息和一个标签,用于存储与两者相关的ID。
<asp:DropDownList ID="ddlMedType" runat="server" DataSourceID="sdsMedType"
DataTextField="MedType" DataValueField="MedType" AppendDataBoundItems="True"
AutoPostBack="True" OnSelectedIndexChanged="ddlMedType_SelectedIndexChanged">
<asp:ListItem Selected="True">Select Medication Type</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sdsMedType" runat="server"
ConnectionString="<%$ ConnectionStrings:SqlDataSource2 %>"
SelectCommand="SELECT [num], [MedType] FROM [pharm_medication_Type]">
</asp:SqlDataSource>
<asp:Label ID="lblMedType" runat="server" Visible="true"/>
<asp:DropDownList ID="ddlMedication" runat="server" DataSourceID="sdsMedication"
DataTextField="MedName" DataValueField="MedName">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsMedication" runat="server"
ConnectionString="<%$ ConnectionStrings:SqlDataSource2 %>"
SelectCommand="SELECT [MedName] FROM [pharm_medications] WHERE ([num] = @num)">
<SelectParameters>
<asp:ControlParameter ControlID="lblMedType" Name="num" PropertyName="Text" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
这里在我后面的代码中填充标签以获取相关表的id
protected void ddlMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string strMedType = ddlMedType.SelectedValue;
SqlCommand cmd1 = new SqlCommand("SELECT [num] from [pharm_medication_Type] where [MedType] = '" + strMedType + "'", conn1);
cmd1.CommandType = CommandType.Text;
conn1.Open();
int Result1 = Convert.ToInt32(cmd1.ExecuteScalar());
lblMedType.Text = Result1.ToString();
conn1.Dispose();
cmd1.Dispose();
}
但是当我运行应用程序时,除第二个选项外,所有选项都有效。为什么呢?
答案 0 :(得分:1)
我建议您直接将ddlMedType
用于<asp:ControlParameter>
,并且不要使用分隔标签来获取ID,只需设置DataTextField
和DataValueField
ddlMedType
正确而且足够。请更改您的代码如下:
<asp:DropDownList ID="ddlMedType" runat="server" DataSourceID="sdsMedType"
DataTextField="MedType" DataValueField="num" AppendDataBoundItems="True"
AutoPostBack="True" OnSelectedIndexChanged="ddlMedType_SelectedIndexChanged">
<asp:ListItem Selected="True" value="0">Select Medication Type</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sdsMedType" runat="server"
ConnectionString="<%$ ConnectionStrings:SqlDataSource2 %>"
SelectCommand="SELECT [num], [MedType] FROM [pharm_medication_Type]">
</asp:SqlDataSource>
<asp:DropDownList ID="ddlMedication" runat="server" DataSourceID="sdsMedication"
DataTextField="MedName" DataValueField="MedName">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsMedication" runat="server"
ConnectionString="<%$ ConnectionStrings:SqlDataSource2 %>"
SelectCommand="SELECT [MedName] FROM [pharm_medications] WHERE ([num] = @num)">
<SelectParameters>
<asp:ControlParameter ControlID="ddlMedType" Name="num" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
并删除事件背后代码的代码如下:
protected void ddlMedType_SelectedIndexChanged(object sender, EventArgs e)
{}
希望这对你有所帮助。