简体   繁体   中英

C#/ASP.NET gridview databind dropdownlist index changed

I am new to .net world and I could not figure out why the below code does not work. I have a dropdownlist populated with DEPARTMENT_NAME and value as DEPARTMENT_ID. I have a gridview which populates the employees data based on department_id selected from dropdown list. I have written the following code but the gridview is not populating. Can someone please help what I am doing wrong here.

protected void ddDepartments_SelectedIndexChanged(object sender, EventArgs e)
        {
            string connStr = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;
            OracleConnection oConn = new OracleConnection(connStr);
            oConn.Open();
            string SqlText = "Select * from employees where department_id = :department_id";

            OracleCommand cmd = new OracleCommand(SqlText, oConn);
            cmd.CommandType = CommandType.Text;

            OracleParameter p_department_id = new OracleParameter();
            p_department_id.OracleDbType = OracleDbType.Varchar2;
            p_department_id.Value = ddDepartments.SelectedItem.Value;

            cmd.Parameters.Add(p_department_id); 

            OracleDataAdapter adapter = new OracleDataAdapter(cmd);
            DataTable dtEmployees = new DataTable();
            adapter.Fill(dtEmployees);

            gvEmployees.DataSource = dtEmployees;
            gvEmployees.DataBind();

            dtEmployees.Dispose();
            adapter.Dispose();
            cmd.Dispose();
            oConn.Close();
            oConn.Dispose();
        }

You need to use a Session variable to persist the gridView datasource on Postback which is sent by the dropdownlist.

So right after:

gvEmployees.DataSource = dtEmployees;
gvEmployees.DataBind();

Add:

Session("gvDS") = gvEmployees.DataSource;

In the page Load() method:

if (Session["gvDS"] != null && IsPostBack)
{
    gvEmployees.DataSource = Session["gvDS"];
    gvEmployees.DataBind();
}
else
    BindGridView();  // you initial gvEmployees binding method

Please see my answer @:

Asp.net Web Forms GridView Dynamic Column Issue

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