DataGrid日期字符串筛选器
本文关键字:筛选 字符串 日期 DataGrid | 更新日期: 2023-09-27 17:59:06
试图获得有关此问题的帮助,我试图用文本框在数据网格中查找特定日期。日期当前是格式为dd/MM/yyyy的字符串。在日期列中。我以前发过帖子,但并没有得到有用的答案,我的问题也被埋没了。似乎没有人有答案——他们只是回避这个话题。目前,我无法将日期设置为DateTime,因为应用程序的其余部分已格式化。
感谢
编辑代码:
public class ImagesInfo
{
public string FileName { get; set; } //For Picture File Name
public string Description { get; set; } //For the Description of the Picture
public string Category { get; set; } //Category of Picture
public string Date { get; set; }//Date Taken of the Picture, format discussed in report.
public string Comments { get; set; } //Comments for the picture
}
我在数据网格中查找类别时使用的代码。
if (categoryFilterBox.Text == string.Empty)
{
//used if nothing is in the filter box to avoid blanking
var source = new BindingSource();
source.DataSource = images;
navigationGrid.DataSource = source;
}
else
{
//making a new filtered list that includes the matching Categorys and binding it.
string catFilter;
try
{
catFilter = categoryFilterBox.Text;
var filteredList = images.Where(item => item.Category == catFilter);
var filterSource = new BindingSource();
filterSource.DataSource = filteredList;
navigationGrid.DataSource = filterSource;
}
catch (FormatException)
{
MessageBox.Show("Must be Words of Letters");
}
}
一个记录被添加到我的列表中的例子,它是数据网格的来源。
private void addRecord()
{
var newImage = new ImagesInfo();//new instance
newImage.FileName = fileNameTextBox.Text;
newImage.Category = categoryComboBox.Text;
//try catch for input of the date
try
{
newImage.Date = dateTakenTextBox.Text;
}
catch (FormatException)
{
MessageBox.Show("Date Not Correct Format");
}
try
{
newImage.Description = descriptionTextBox.Text;
}
catch (FormatException)
{
MessageBox.Show("Must user letters and words");
}
try
{
newImage.Comments = commentsTextBox.Text;
}
catch (FormatException)
{
MessageBox.Show("Must use letters and words");
}
images.Add(newImage);//Add instance to the main list
if (editCheckBox.Checked)
{
//Binding the new updated list to the datagrid
var source = new BindingSource();
source.DataSource = images;
navigationGrid.DataSource = source;
}
}
编辑:我现在怎么会得到它,但它似乎不起作用。
if (startDate.Text == string.Empty)
{
var source = new BindingSource();
source.DataSource = images;
navigationGrid.DataSource = source;
}
else
{
string dateFilter = startDate.Text;
var filteredList = images.Where(item => item.Date == dateFilter);
var filterSource = new BindingSource();
filterSource.DataSource = filteredList;
navigationGrid.DataSource = filterSource;
}
试试这个:
DateTime temp;
// try to parse the provided string in order to convert it to datetime
// if the conversion succeeds, then build the dateFilter
if(DateTime.TryParse(TrystartDate.Text, out temp))
{
string dateFilter = temp.ToString("dd/MM/yyyy");
var filteredList = images.Where(item => item.Date == dateFilter);
var filterSource = new BindingSource();
filterSource.DataSource = filteredList;
navigationGrid.DataSource = filterSource;
}