Search code examples
c#asp.netc#-4.0c#-3.0using-statement

'System.Data.DataRowView' in DropDownList


I cannot bind data to a Dropdown List.. Can any one explain me why? Error is : 'System.Data.DataRowView' does not contain a property with the name '_DeptID'. my code is:

public class ClassDataManagement
{
    public DataTable BindDropDownList(string Sql, DropDownList DropDownList)
    {
        SqlConnection cn = new SqlConnection(@"Data Source=ABID-PC;Initial Catalog=_uniManagement;Integrated Security=True");
        SqlCommand cmd = new SqlCommand(Sql, cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count == 0)
        {

        }
        else
        {
            DropDownList.DataTextField = "Name";
            DropDownList.DataValueField = "_DeptID";
            DropDownList.DataSource = dt.DefaultView;
            DropDownList.DataBind();
        }
        return dt;
    }

}
protected void Page_Load(object sender, EventArgs e)
{
    ClassDataManagement dm = new ClassDataManagement();
    dm.BindDropDownList("select _Program.Name from _program,_Department where _program._Deptid = _department._DeptId", DropDownListProgram);
}

Solution

    1. The column _Dept is missing in your select statement
    2. Disposing of the objects is missing. So you can perform it in two ways

      (a) Manually disposing

      (b) Using Statement


    public class ClassDataManagement
    {
        public DataTable BindDropDownList(string Sql, DropDownList DropDownList)
        {
            using (SqlConnection cn = new SqlConnection(@"Data Source=ABID-PC;Initial Catalog=_uniManagement;Integrated Security=True"))
            {
                using (SqlCommand cmd = new SqlCommand(Sql, cn))
                {
                    using(SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        using (DataTable dt = new DataTable())
                        {
                            da.Fill(dt);
                            DropDownList.DataTextField = "Name";
                            DropDownList.DataValueField = "_Deptid";
                            DropDownList.DataSource = dt.DefaultView;
                            DropDownList.DataBind();
                            return dt;
                        }
                    }
                }
            }
        }
    
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        ClassDataManagement dm = new ClassDataManagement();
        dm.BindDropDownList("select _Program.Name, _program._Deptid from _program,_Department "
            + "where _program._Deptid = _department._DeptId", DropDownListProgram);
    
    }
    

    EDIT - 1

    Adding the Using Statement for SqlDataAdapter as well