简体   繁体   中英

How to bind selected value from database in dropdownlist in asp.net

I am trying to bind a selected item from the database in dropdownlist. I am not getting the users selected data in the dropdownlist instead it loads everything. What i need is to have a default selected value from the database along with other items. Please help me to overcome this problem. Thanking you in advance.

Stored procedure:

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 markup:

<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"/>

My code behind:

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();
    }
}

You have to use SelectedValue property of DropDownList . DataTextField and DataValueField are for specifying which properties from DataSource should be used as Text and Value of drop down list.

Replace these lines:

ddlInstitute.DataValueField= dr["InstituteId"].ToString();
ddlInstitute.DataTextField= dr["Institute"].ToString();

with:

ddlInstitute.SelectedValue= dr["InstituteId"].ToString();

or you can also do:

ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;

You can also refer this article

假设您知道要选择哪个 ID,请尝试以下操作:

ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;

Try it as a function:

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"));
}

In function:

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;
        }
    }
}

Use stored procedure in the function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM