2012-03-15 18 views
2

你好,我前幾天發佈了一個類似的問題,我被告知使用數據集篩選器來篩選我的datagridview。我已經走了,但我正在努力研究如何去做。2個日期之間的數據集篩選

我想通過2 datetimepickers - startDate和endDate篩選datagridview中的截止日期列。

datagridview的是TaskTable2,datetimepicker1是startSchedule,datetimepicker2是endSchedule和截止日期的datagridview被deadlineRow

TaskDataSet在基礎數據源。

到目前爲止,我已經得到了以下代碼,它成功地使行不可見,不在選定的開始和結束日期之間。

private void scheduleButton_Click(object sender, EventArgs e) 
    { 

     DateTime startSchedule = startDate.Value.Date; 
     DateTime endSchedule = endDate.Value.Date; 

     if (startSchedule <= endSchedule)// runs foreach loop if startdate and enddate are valid 
     { 
      foreach (DataGridViewRow dr in TaskTable2.Rows)// loops through rows of datagridview 
      { 
       string deadline = dr.Cells["Deadline"].Value.ToString(); // gets deadline values 
       DateTime deadlineRow = Convert.ToDateTime(deadline); // converts deadline string to datetime and stores in deadlineRow variable 

       if (startSchedule <= deadlineRow && deadlineRow <= endSchedule) // filters deadlines that are => startDate and <= endDate 
       { 
        dr.Visible = true; // display filtered rows here. 
       } 
       else 
       { 
        dr.Visible = false; // hide rows that are not beteen start and end date. 
        TaskTable2.CurrentCell = null; 
       } 

      } 
     } 
     else 
     {  
      MessageBox.Show("Please ensure Start Date is set before End Date."); // ensures user selects an end date after the start date. 
     } 
    } 

但是,我有幾個存在的問題:

  1. 使用Visible屬性是錯誤的做法,我需要使用類似以下(過濾數據集不知道該怎麼辦呢)

    TaskDataSet.Filter = "startSchedule <= Deadline AND Deadline <= endSchedule"; 
    
  2. 我是應該打印過濾 結果打印按鈕。但是,它正在打印存儲在 datagridview中的所有數據,即使某些行可見=從按日期按鈕 開始的false,所以這就是爲什麼我需要過濾數據集,然後在打印事件中使用 。

在DataGridView綁定到一個XML文件,以便數據可以從datagridview的用於過濾和印刷aslong它們保持在XML文件中被刪除。

如果有人可以修改我的代碼與數據集過濾器,而不是使用可見屬性,將不勝感激。

謝謝!

回答

2

您過濾代碼可能是:

DateTime startSchedule = startDate.Value.Date; 
DateTime endSchedule = endDate.Value.Date; 

TaskDataSet.Filter = "Deadline >='" + startSchedule + "' AND Deadline <= '" + endSchedule + "'"; 

至於你與篩選結果的打印第二個問題 - 在VB.NET網上發現了這個鏈接,但你可以將其轉換爲C#

Print DataSet or DataTable contents from VB.NET

您也可以嘗試DataSet.Clone()並遍歷行以刪除過濾的項目,然後打印剩餘的記錄。

DataGridView Printing by Selecting Columns/Rows

How can I print data from a DataGridView in C#?

+0

難道我在你發佈第二連桿使用if語句一樣 - 如果(!GridCol.Visible),以篩選出有明顯的行數=假印刷? – Rob 2012-03-15 17:29:31

+0

@Rob你將不得不測試它,看看它會工作。我的任何應用程序中都沒有打印。 – Taryn 2012-03-15 17:31:10

-2

假設你的數據集被命名爲「DS」和將數據存儲在第一個表,你可以這樣做:

ds.Tables[0].DefaultView.RowFilter = 
    string.Format("Deadline between ({0}, {1})",startSchedule,endSchedule); 

請注意,我沒有測試這一點。

+0

之間的數據表不支持濾鏡 – 2017-04-27 13:16:16