添加行号:
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//点击其他单元格
{
}
}