我正在尝试从下拉列表的数据库中绑定选定的项目。我没有在下拉列表中让用户选择数据,而是加载了所有内容。我需要的是从数据库中获得默认的选定值以及其他项目。请帮助我克服这个问题。预先感谢您。
存储过程:
CREATE PROCEDURE [dbo].[get_student_details]
@StudentId int = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT
dbo.Student.InstituteId,
dbo.Student.Institute,
dbo.Student.Name,
dbo.Student.Gender,
dbo.Student.Age
FROM
dbo.Student
WHERE
dbo.Student.StudentId = @StudentId
END
我的.aspx标记:
<asp:DropDownList ID="ddlInstitute" runat="server"></asp:DropDownList>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:Button ID="btnPersonalDetails" runat="server" Text="Search" OnClick="GetStudentDetails"/>
我后面的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillInstitute();
}
}
public void FillInstitute()
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "get_Institute";
cmd.Connection = con;
try
{
con.Open();
ddlInstitute.DataSource = cmd.ExecuteReader();
ddlInstitute.DataTextField = "Institute";
ddlInstitute.DataValueField = "InstituteId";
ddlInstitute.DataBind();
ddlInstitute.Items.Insert(0, new ListItem("--Select--", "0"));
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
public void GetStudentDetails()
{
studentid= 123;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "get_student_details";
cmd.Parameters.Add("@StudentId", SqlDbType.Int).Value = studentid;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
ddlInstitute.DataValueField= dr["InstituteId"].ToString();
ddlInstitute.DataTextField= dr["Institute"].ToString();
txtName.Text = dr["Name"].ToString();
txtGender.Text = dr["Gender"].ToString();
txtAge.Text = dr["Age"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
最佳答案
您必须使用SelectedValue
的DropDownList
属性。DataTextField
和DataValueField
用于指定DataSource
中的哪些属性应用作文本和下拉列表的值。
替换这些行:
ddlInstitute.DataValueField= dr["InstituteId"].ToString();
ddlInstitute.DataTextField= dr["Institute"].ToString();
与:
ddlInstitute.SelectedValue= dr["InstituteId"].ToString();
或者您也可以:
ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;
您也可以参考this article
关于c# - 如何从asp.net的下拉列表中的数据库绑定(bind)选定的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32528561/