C# 如何在asp.net的dropdownlist中绑定数据库中的选定值
我正在尝试绑定dropdownlist中数据库中的选定项。我没有在dropdownlist中获取用户选择的数据,而是加载所有内容。我需要的是从数据库和其他项目中选择一个默认值。请帮我克服这个问题。先谢谢你 存储过程:C# 如何在asp.net的dropdownlist中绑定数据库中的选定值,c#,asp.net,data-binding,C#,Asp.net,Data Binding,我正在尝试绑定dropdownlist中数据库中的选定项。我没有在dropdownlist中获取用户选择的数据,而是加载所有内容。我需要的是从数据库和其他项目中选择一个默认值。请帮我克服这个问题。先谢谢你 存储过程: CREATE PROCEDURE [dbo].[get_student_details] @StudentId int = 0 AS BEGIN SET NOCOUNT ON; SELECT dbo.Student.Institut
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
My.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"/>
您必须使用的属性。和用于指定应将中的哪些属性用作下拉列表的文本和值
更换这些线路:
ddlInstitute.DataValueField= dr["InstituteId"].ToString();
ddlInstitute.DataTextField= dr["Institute"].ToString();
与:
或者,您也可以执行以下操作:
ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;
您也可以参考假设您知道要选择哪个ID,请尝试以下操作:
ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;
将其作为一个函数进行尝试:
void FN_loadBranch()
{
classname cls = new classname ();
DataTable dt = new DataTable();
dt = cls.FUNCTIONNAMEINCLASS(int id);
dropdown.DataSource = dt;
dropdown.DataValueField = "valuefield";
dropdown.DataTextField = "textfield";
dropdown.DataBind();
ddlBranch.Items.Insert(0, new ListItem("--Select--", "0"));
}
public DataTable FUNCTIONNAMEINCLASS( int id)
{
try
{
using (SqlConnection cn = new SqlConnection(CLASS.ConnectionString))
{
SqlCommand cmd = new SqlCommand("[storedprocedure]", cn);
cn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ID", SqlDbType.VarChar, 50).Value = id;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
在功能上:
void FN_loadBranch()
{
classname cls = new classname ();
DataTable dt = new DataTable();
dt = cls.FUNCTIONNAMEINCLASS(int id);
dropdown.DataSource = dt;
dropdown.DataValueField = "valuefield";
dropdown.DataTextField = "textfield";
dropdown.DataBind();
ddlBranch.Items.Insert(0, new ListItem("--Select--", "0"));
}
public DataTable FUNCTIONNAMEINCLASS( int id)
{
try
{
using (SqlConnection cn = new SqlConnection(CLASS.ConnectionString))
{
SqlCommand cmd = new SqlCommand("[storedprocedure]", cn);
cn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ID", SqlDbType.VarChar, 50).Value = id;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
在函数中使用存储过程很高兴它对@apurbaf有帮助。最后,FindByText()为我修复了它。