[英]C# drop down list selected value not being set to SQL select statement stored procedure
I have a data-bound drop-down list of collegeID values and I want to select one of these values based on a collegeID in an SQL database.我有一个 collegeID 值的数据绑定下拉列表,我想要 select 这些值之一基于 SQL 数据库中的 collegeID。 I have a stored procedure to select the ID, but the value is not being selected when the page is run.
我有一个 ID 为 select 的存储过程,但在页面运行时未选择该值。
My SQL stored procedure is as follows:我的SQL存储过程如下:
USE [CONNECTION]
GO
/****** Object: StoredProcedure [db_owner].[CollegePersonSelectAll] Script Date: 5/9/2022 10:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Alexander Johnson
-- Create date: 5/9/2022
-- Description: CollegePersonSelectAll
-- =============================================
ALTER PROCEDURE [db_owner].[CollegePersonSelectAll]
-- Add the parameters for the stored procedure here
@personID int,
@collegeID int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT collegeID
FROM CollegePerson
WHERE personID = @personID
END
The code in C# is as follows: C#中的代码如下:
protected void Page_Load(object sender, EventArgs e)
{
personID = RetrieveID();
if (!Page.IsPostBack)
{
string dbConn = System.Configuration.ConfigurationManager.ConnectionStrings["CONNECTIONSTRING"].ConnectionString;
SqlConnection conn = new SqlConnection(dbConn);
using (SqlCommand cmd = new SqlCommand("[CollegePersonSelectAll]", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@personID", personID);
try
{
conn.Open();
_updateCollege.SelectedValue = Convert.ToString(cmd.ExecuteScalar());
collegeID = Convert.ToString(cmd.ExecuteScalar());
}
catch (SqlException ex)
{
this._message.Text = "Error from SQL " + ex.Message;
}
}
}
}
The HTML for the dropdown list is as follows:下拉列表的HTML如下:
<asp:DropDownList ID="_college" runat="server" DataSourceID="sqlDataCollege" DataTextField="collegeName" DataValueField="collegeID" Width="157px" AppendDataBoundItems="True">
<asp:ListItem Value="0" SelectedValue='%#bind("stateAbbrev")%>'>-Please Select-</asp:ListItem>
</asp:DropDownList>
The _updateCollege.SelectedValue
does not show the value from the database. _updateCollege.SelectedValue
不显示数据库中的值。 Does anyone know why this is?有人知道为什么吗?
Remove @collegeID
from the input parameter and use ExecuteScalar
instead of ExecuteNonQuery
.从输入参数中删除
@collegeID
并使用ExecuteScalar
而不是ExecuteNonQuery
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.