I have two problems. 1st problem is after filter the rows when I export to excel it gives me all data with out filter applied.
the second is how to filter using b/n two dates? ```(dgvEmployeeList.DataSource as DataTable).DefaultView.RowFilter = string.Format("date?????);
DataGridView Filter
private void btnSearchEmployeeType_Click(object sender, EventArgs e)
{
string searchValue = cbSearchByEmployeeType.Text;
try
{
(dgvEmployeeList.DataSource as DataTable).DefaultView.RowFilter = string.Format("EmployeeType like '%" + searchValue + "%'");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
Export DataGridView
private void btnExportExcel_Click(object sender, EventArgs e)
{
using ( XLWorkbook workbook = new XLWorkbook())
{
workbook.Worksheets.Add((dgvEmployeeList.DataSource as DataTable), "Employees");// here is the problem
workbook.SaveAs(sfd.FileName);
MessageBox.Show("You Have Successfully Exported your Data to an Excel File", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
any help! thanks
To set up a RowFilter
with dates enclose the date value strings with # characters. To avoid problems with current culture format the dates with their ToString()
to be sure the filter parser will understand it. See PoC below.
[TestMethod]
public void MyTestMethod()
{
var dt = new DataTable();
dt.Columns.Add(new DataColumn("dt", typeof(DateTime)));
dt.Rows.Add(new object[] { new DateTime(1999, 01, 01) });
dt.Rows.Add(new object[] { new DateTime(2000, 02, 01) });
dt.Rows.Add(new object[] { new DateTime(2001, 03, 01) });
dt.Rows.Add(new object[] { new DateTime(2002, 04, 01) });
var startDate = new DateTime(2000, 01, 01);
var endDate = new DateTime(2001, 01, 01);
// use date strings between # signs and
// formatted via current culture to be sure it is parseable
dt.DefaultView.RowFilter = $"dt >= #{startDate}# AND dt <= #{endDate}#";
var r = dt.DefaultView.ToTable();
Assert.IsTrue(r.Rows
.Cast<DataRow>()
.Select(i => (DateTime)i[0])
.All(j => j >= startDate && j <= endDate));
}
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.