How remove records from datagrid in asp.net if con

2020-03-31 06:55发布

问题:

I have a datagrid declare like this in ascx file:

<asp:datagrid id="dgCompanies" Width="100%" AllowSorting="True" DataKeyField="companyId" AutoGenerateColumns="False"
            AllowPaging="True" AllowCustomPaging="True" OnPageIndexChanged="dgCompanies_Paging" Runat="server" onprerender="dgCompanies_PreRender" >

basically, datagrid is the search result some how like this in codebehind:

// retrieve the matching company records
        IDataReader rdr = Syntegra.Manufacturing.WMCCM.Companies.Companies.ListCompanies(dgCompanies.CurrentPageIndex, pageSize, CompanyList, CompanyNameStartsWith, ProcessSqlClause, SkillSqlClause, LocationClause, KeywordSqlClause, User, Status, SearchPortalId, false, sortColumn, sortDirection);

        // highlight the sorted column
        highlightSortColumn();

        if (rdr.Read())
        {
            // calculate page details
            _count = (int) rdr["companyCount"];

            this.dgCompanies.VirtualItemCount = _count;


            // move onto the next resultset
            rdr.NextResult();

            // bind the data to the datagrid
            dgCompanies.PageSize = pageSize;
            dgCompanies.DataSource = rdr;
            dgCompanies.DataBind();

I will need to check if companyId is not equal to some values, then I need to remove that record from the search result, meaning remove it from that dgCompanies datagrid. I really have no idea I could do that, could anyone please give me some help here?

回答1:

You cannot directly filter the IDataReader since it will be read like one by one.

What you can simply do is load all the data from datareader into DataTable using a Load() method.

IDataReader rdr = Syntegra.Manufacturing.WMCCM.Companies.Companies.
                  ListCompanies(dgCompanies.CurrentPageIndex, pageSize, CompanyList,
                  CompanyNameStartsWith, ProcessSqlClause, SkillSqlClause, 
                  LocationClause, KeywordSqlClause, User, Status, SearchPortalId, false, 
                  sortColumn, sortDirection);
DataTable dt = new DataTable();
dt.(rdr);
//For filtering all the CompanyID column value not equal to  5
DataRow[] filteredRows=DataTable.Select("[CompanyID] <> 5 " ); 

dgCompanies.PageSize = pageSize;
dgCompanies.DataSource = filteredRows;
dgCompanies.DataBind();


回答2:

Good practice is to populate datareader based on required criteria.

In case you want to filter records from datareader, you can load it into datatable.

IDataReader rdr = Syntegra.Manufacturing.WMCCM.Companies.Companies.ListCompanies(dgCompanies.CurrentPageIndex, pageSize, CompanyList, CompanyNameStartsWith, ProcessSqlClause, SkillSqlClause, LocationClause, KeywordSqlClause, User, Status, SearchPortalId, false, sortColumn, sortDirection);
DataTable dt = new DataTable();
dt.Load(rdr);
rdr.Close();


for(int i = dt.Rows.Count-1; i >= 0; i--)
{
   DataRow dr = dt.Rows[i];

   int iCompanyId = Convert.ToInt(dr["CompanyId"]);

   if (IsCompanyHavingChoiceYes(iCompanyId))
    dr.Delete();
}   


dt.AcceptChanges();

dgCompanies.PageSize = pageSize;
dgCompanies.DataSource = dt;  //provide datatable as datasource
dgCompanies.DataBind();

Method to check from database:

private  bool IsCompanyHavingChoiceYes(int iCompanyId)
    {            
        string commandText = @"SELECT cn.companyId from companies cn 
                   INNER JOIN UserCompany uc ON uc.companyid = cn.companyid 
                   INNER JOIN Users u ON u.userId = uc.userId
                   INNER JOIN Choice c ON c.Email = u.Email And c.Choice = @Choice
                   WHERE cn.CompanyId = @CompanyId;";

        string connectionString = ConfigurationSettings.AppSettings["connectionString"];

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(commandText, connection);
            command.Parameters.AddWithValue("@CompanyId", iCompanyId);
            command.Parameters.AddWithValue("@Choice", "YES");

            try
            {
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    return reader.HasRows;
                }

                return false;
            }
            catch (Exception ex)
            {
                return false;
            }

        }
    }

http://i.stack.imgur.com/rPy3A.png