reza
reza

Reputation: 29

How to Get DropDownList selected text and Fill details in GridView and labels based on that in asp.net

I have an ASP.NET site with a SQL Server 2008 database. I want to select the text of a dropdownlist and fill details in GridView and labels based on that, but when I select an item of selected text it does not fill details in GridView and labels.

Notice that my drop downlist is list of months. How can I fix this problem?

My code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class form : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["emp_dbConnectionString"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void ddlEmpRecord_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    private void BindEmpGrid()
    {
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();
        try
        {
            SqlCommand cmd = new SqlCommand("select * from shakhes where mah_tadieh=" + ddlEmpRecord.Text + " ", con);
            adp.SelectCommand = cmd;
            adp.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                grdEmp.DataSource = dt;
                grdEmp.DataBind();
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
        }
        finally
        {
            dt.Clear();
            dt.Dispose();
            adp.Dispose();

        }
    }
    protected void ddlEmpRecord_TextChanged(object sender, EventArgs e)
    {
        BindEmpGrid();
    }
}

Upvotes: 0

Views: 183

Answers (1)

JCM
JCM

Reputation: 105

Use SelectedIndexChanged event instead of TextChanged event, and make sure your DropDownList AutoPostBack property is set to "true".

protected void ddlEmpRecord_SelectedIndexChanged(object sender, EventArgs e)
{
    BindEmpGrid();
}

Hope it helps.

Upvotes: 1

Related Questions