C#--DataGridView的使用

添加行号:

在这里插入图片描述

private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
    if(dataGridView1.Rows.Count>1)
     e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
}

添加一行数据:

dataGridView1.SuspendLayout();
int index = this.dataGridView1.Rows.Add();
for (int i = 0; i < data.Count; i++)
{
    this.dataGridView1.Rows[index].Cells[i].Value = data[i];
}
dataGridView1.ResumeLayout();

绑定数据源:

dataGridView1.DataSource = table;

还有属性设置:
在这里插入图片描述

设置列名:

dataGridView1.Columns[i].HeaderText = value;
dataGridView1.Columns["col1"].HeaderText = value;

导出表格数据为Excel或Txt

public bool ExportToExcelOrTxt(DataGridView dgvData, string fileName, List<string>columns)
{
     StreamWriter sw = new StreamWriter(fileName, false,Encoding.GetEncoding(-0));
     string str = "";
     try
     {
         //写标题
         for (int i = 0; i < dgvData.ColumnCount; i++)
         {
            
             var title = dgvData.Columns[i].HeaderText;
             if (columns.Contains(title))
             {
                 if (!string.IsNullOrEmpty(str))
                 {
                     str += "\t";
                 }
                 str += dgvData.Columns[i].HeaderText;
             }
                 
         }
         //str += "\t" + "时间戳";
         sw.WriteLine(str);
         //写内容
         for (int j = 0; j < dgvData.Rows.Count; j++)
         {
             string tempStr = "";
             DateTime time = default;
             for (int k = 0; k < dgvData.Columns.Count; k++)
             {
                 if (columns.Contains(dgvData.Columns[k].HeaderText))
                 {
                     if (!string.IsNullOrEmpty(tempStr))
                     {
                         tempStr += "\t";
                     }
                     string cellValue = dgvData.Rows[j].Cells[k].Value?.ToString();
                     if (cellValue == null)
                     {
                         continue;
                     }
                     if (cellValue.Length > 8 && DateTime.TryParse(cellValue, out DateTime time1))
                     {
                         time = time1;
                     }
                     cellValue = cellValue.Replace(" ", "");
                     cellValue = cellValue.Replace("\r", "");
                     cellValue = cellValue.Replace("\n", "");
                     cellValue = cellValue.Replace("\r\n", "");
                     tempStr += cellValue;
                 }
                 // tempStr += dgvData.Rows[j].Cells[k].Value.ToString();
             }
             //DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
             //long timeStamp = (long)(time - startTime).TotalSeconds; // 相差秒数
             //tempStr += "\t" + timeStamp;
             sw.WriteLine(tempStr);
         }
         MessageBox.Show("导出成功");
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
         return false;
     }
     finally
     {
         sw.Close();
     }

     return true;
 }

问题汇总:

DataGridView数据源更换或刷新时,表格内容不显示或者不变

有关修改颜色:

修改标题颜色

dataGridView1.EnableHeadersVisualStyles = false;//必须设置

dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Red;

添加按钮:

在这里插入图片描述

在这里插入图片描述
效果:
在这里插入图片描述

点击获取单元格的值

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int Index = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引

            if (Index < this.dataGridView1.Rows.Count - 1)
                return;
            var value = dataGridView1.Rows[e.RowIndex].Cells["Name"].Value;
        }

区分按钮和其他单元格点击事件

 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
     int Index = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引

     if (Index < this.dataGridView1.Rows.Count - 1)
                return;
     if(dataGridView1.CurrentCell.FormattedValue.ToString() == "删除")//点击按钮
      {                               
          
      }
     else//点击其他单元格
     {
         

     }
 }
  • 4
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yyuanyuxin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值