Tima'a Tamim Tima'a Tamim - 3 months ago 7
C# Question

Clearing data grid view after each selection of comboBox to retrive new data

I have three categories in my employee view form and they are :

1- All Employee

2- Manager

3- Employee

These three categories are set as items in a comboBox each time I select one of the items it should display data about the selected item ... the problem is that the data grid view doesn't clear its first data to retrive the new one

my codes in the constructor is for displaying all employees

da = new SqlDataAdapter("select empId as ID,empName ,empAdd,empBdate,empPhone1,empPhone2,empEmail,empSSN,empQualf from emp", cn);
da.Fill(dt);
empViewdgv.DataSource=dt;


and the other codes for retriving employee data on selection of combobox items

private void empViewcmbo_SelectedIndexChanged(object sender, EventArgs e)
{
if (empViewcmbo.SelectedIndex == 0)
{
empViewdgv.DataSource = null;
empViewdgv.Rows.Clear();
da = new SqlDataAdapter("select empId as ID,empName ,empAdd,empBdate,empPhone1,empPhone2,empEmail,empSSN,empQualf from emp", cn);
da.Fill(dt);
empViewdgv.DataSource = dt;
}
else if (empViewcmbo.SelectedIndex == 1)
{
empViewdgv.DataSource = null;
empViewdgv.Rows.Clear();
da = new SqlDataAdapter("select empId as ID,empName ,empAdd,empBdate,empPhone1,empPhone2,empEmail,empSSN,empQualf from emp where empPerm='Manager'", cn);
da.Fill(dt);
empViewdgv.DataSource = dt;

}
else if (empViewcmbo.SelectedIndex == 2)
{
empViewdgv.DataSource = null;
empViewdgv.Rows.Clear();
da = new SqlDataAdapter("select empId as ID,empName ,empAdd,empBdate,empPhone1,empPhone2,empEmail,empSSN,empQualf from emp where empPerm='Employee'", cn);
da.Fill(dt);
empViewdgv.DataSource = dt;
}
}


When I select all employees it should display all employees but if I select Manager it should empty the data from datagridview first then display the data of managers and so on ...

Answer

call the Clear() method on DataTable before filling it up like

da = new SqlDataAdapter("select empId as ID,......", cn);
            dt.Clear();
            da.Fill(dt);
            empViewdgv.DataSource=dt;