如何根据两个单元格中的值在DataGridView中绘制选定的行?

时间:2017-04-05 23:14:35

标签: c# winforms datagridview datagridviewcolumn paintevent

我使用分号分隔的文本文件填充DataGridView,如下所示:

private void ExistingAppntmntRecs_Load(object sender, EventArgs e)
{
    DataTable dt = SeparatedValsFileToDataTable(APPOINTMENTS_FILE_NAME, ";");
    dataGridViewExistingAppntmntRecs.DataSource = dt;
}

// from http://stackoverflow.com/questions/39434405/read-csv-to-datatable-and-fill-a-datagridview (Frank)
public static DataTable SeparatedValsFileToDataTable(string filename, string separatorChar)
{
    var table = new DataTable("Filecsv");
    using (var sr = new StreamReader(filename, Encoding.Default))
    {
        string line;
        var i = 0;
        while (sr.Peek() >= 0)
        {
            try
            {
                line = sr.ReadLine();
                if (string.IsNullOrEmpty(line)) continue;
                var values = line.Split(new[] { separatorChar }, StringSplitOptions.None);
                var row = table.NewRow();
                for (var colNum = 0; colNum < values.Length; colNum++)
                {
                    var value = values[colNum];
                    if (i == 0)
                    {
                        table.Columns.Add(value, typeof(String));
                    }
                    else
                    { row[table.Columns[colNum]] = value; }
                }
                if (i != 0) table.Rows.Add(row);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            i++;
        }
    }
    return table;
}

我现在想要做的是在当前日期黄色的两个月内,在一个月内橙色,以及过去日期(意味着它们已经过去)的红色的行中,显示具有EndDate值的行。 / p>

有一个可能有效的PostPaint事件,但我不知道如何检查该事件处理程序中行内的单元格内容:

private void dataGridViewExistingAppntmntRecs_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    // What now?
}

以下是读取的文件内容(伪造/测试数据,标题行前置):

person;phone;email;org;addr1;addr2;city;st8;zip;visitNum;success;adSizeLoc;meetingLoc;meetingDate;meetingTime;adBeginMonth;adBeginYear;adEndMonth;adEndYear;Notes
B.B. King;2221113333;bbking@blues.com;Virtuosos;1234 Wayback Lane;;Chicago;IL;98765;1;false;Full Page Inside Front Cover;Same as Org Address;4/5/2017 2:03:12 PM;9:00 am;May;2017;May;2018;Lucille was her name
Linda Ronstadt;55577889999;rhondalinstadt@eaglet.com;Eagles Singer;La Canada;;Los Angeles;CA;99988;1;false;Full page Inside Back Cover;Same as Org Address;4/5/2017 2:05:23 PM;9:00 am;May;2017;May;2018;She had some good stuff

如果adEndMonth + adEndYear日期相当于2个月或更短的距离,则整行应为黄色;如果1个月或更短的距离,橙色;如果今天或过去,把它漆成红色。最后,如果滚石之一正在运行应用程序,则将其涂成黑色。

这是PostPaint事件的一些伪代码,带有“TODO:”,我不知道该怎么做:

private void dataGridViewExistingAppntmntRecs_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    DateTime twoMonthsLimit = DateTime.Now.AddMonths(2);
    DateTime oneMonthLimit = DateTime.Now.AddMonths(1);
    int endYear = // TODO: assign adEndYear value
    int endMonth = // TODO: assign adEndMonth value
    DateTime endDate = new DateTime(endYear, endMonth, 1);
    if (twoMonthsLimit > endDate) // TODO: paint row yellow
    if (oneMonthLimit > endDate) // TODO: paint row orange
    if (endDate < DateTime.Now) // TODO: paint row red
}

1 个答案:

答案 0 :(得分:2)

如果目标过于简单,请突出显示属于特定日期的行,然后更改行背景颜色可能更容易。重新绘制行可能是不必要的。我的解决方案只是根据“endMonth”和“endYear”列中的日期更改行背景颜色。

单元格格式化是一个选项,但是,它会经常触发,并且每次更改或显示单元格时都不需要进行“着色”检查。如果行已经“着色”,那么唯一要查找的是添加新行或更改“endMonth”或“endYear”列中的值。

下面是代码,它只是循环遍历DataGridView并根据您描述的标准设置每一行颜色。获得行颜色的逻辑相当简单(减去漆黑)。如果日期从今天的日期开始超过两个月,则将背景颜色保留为白色。如果日期大于1个月但少于2个月,则将行涂成黄色......等等。

我使用类似的方法来读取文本文件并创建DataTable。希望这会有所帮助。

DataTable dt;
string filePath = @"D:\Test\Artist.txt";
char delimiter = ';';

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  dt = GetTableFromFile(filePath, delimiter);
  dataGridViewExistingAppntmntRecs.DataSource = dt;
  UpdateDataGridColors();
}

private DataTable GetTableFromFile(string filePath, char delimiter) {
  List<string[]> allArtists = GetArtistList(filePath, delimiter);
  DataTable dt = GetTableColumns(allArtists[0]);
  int totalCols = dt.Columns.Count;
  DataRow dr;
  for (int i = 1; i < allArtists.Count; i++) {
    string[] curArtist = allArtists[i];
    dr = dt.NewRow();
    for (int j = 0; j < totalCols; j++) {
      dr[j] = curArtist[j].ToString();
    }
    dt.Rows.Add(dr);
  }
  return dt;
}

private List<string[]> GetArtistList(string inFilePath, char inDelimiter) {
  string pathToFile = inFilePath;
  char delimiter = inDelimiter;
  List<string[]> listStringArrays = File.ReadAllLines(pathToFile).Select(x => x.Split(delimiter)).ToList();
  return listStringArrays;
}

private DataTable GetTableColumns(string[] allHeaders) {
  DataTable dt = new DataTable();
  foreach (string curHeader in allHeaders) {
    dt.Columns.Add(curHeader, typeof(string));
  }
  return dt;
}

private Color GetColorForRow(DataRowView dr) {
  // paint it black ;-)
  if (dr[0].ToString().Equals("Rolling Stones")) {
    return Color.Black;
  }
  DateTime rowDate;
  DateTime dateNow = DateTime.Now;
  DateTime twoMonthsLimit = dateNow.AddMonths(2);
  DateTime oneMonthLimit = dateNow.AddMonths(1);
  if (dr != null) {
    string rowStringMonth = dr[17].ToString();
    string rowStringYear = dr[18].ToString();
    string rowStringDate = "1/" + rowStringMonth + "/" + rowStringYear;
    if (DateTime.TryParse(rowStringDate, out rowDate)) {
      if (rowDate > twoMonthsLimit)
        return Color.White;
      if (rowDate > oneMonthLimit)
        return Color.Yellow;
      if (rowDate > dateNow)
        return Color.Orange;
      if (rowDate.Month == dateNow.Month && rowDate.Year == dateNow.Year)
        return Color.Orange;
      // this row date is less than todays month date
      return Color.Red;
    } // else date time parse unsuccessful - ignoring
  }
  // date is null
  return Color.White;
}

private void UpdateDataGridColors() {
  Color rowColor;
  DataRowView dr;
  foreach (DataGridViewRow dgvr in dataGridViewExistingAppntmntRecs.Rows) {
    dr = dgvr.DataBoundItem as DataRowView;
    if (dr != null) {
      rowColor = GetColorForRow(dr);
      dgvr.DefaultCellStyle.BackColor = rowColor;
      if (rowColor == Color.Black)
        dgvr.DefaultCellStyle.ForeColor = Color.White;
    }
  }
}

private void dataGridViewExistingAppntmntRecs_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
  if (e.ColumnIndex == 17 || e.ColumnIndex == 18) {
    //MessageBox.Show("End Date Changed");
    UpdateDataGridColors();
  }
}

private void dataGridViewExistingAppntmntRecs_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) {
  UpdateDataGridColors();
}