wtuqi
3/5/2020 - 9:25 AM

DatagridView

//自动换行
dataGridView1.DefaultCellStyle.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
//自动列宽 
DataGridView1.Columns(3).AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells //要和数据区域自适应列宽混用AutoSizeColumnsMode要放在之后使用
dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; //所有自适应
//数据自动适应DataGridView宽度  宽度自动满屏
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
//自动行高
//在需要换行的内容处添加:System.Environment.NewLine 或者把TextBox设成多行读取到/r/n标志会换行
dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCellsExceptHeader;
//所有内容居中       
dataGridView1.DefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; 
DG.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //表头居中
//因为有小排序小箭头,所以表头看起来字体居中后还偏左,
foreach (DataGridViewColumn col in DG.Columns)//循环排序去小箭头
{
    col.SortMode = DataGridViewColumnSortMode.NotSortable;
}
DG.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //单元格居中
//X列内容居中
dataGridView1.Columns[0].DefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[0].SortMode= System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//指定焦点行
dataGridView1.ClearSelection();
dataGridView1.Rows[3].Selected = true;
//设置DataGridView文本居中
DaatGridView.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
//设置单元格字体颜色,单元格背景色
DataGridView1.EnableHeadersVisualStyles = false; //前题条件
dataGridView1.Rows[i].Cells[13].Style.ForeColor = Color.Red;
dataGridView1.Rows[i].Cells[2].Style.BackColor= Color.Blue;
dataGridView1.Columns[2].HeaderCell.Style.BackColor = Color.Azure;//修改列头背景色
dataGridView1.Columns[2].HeaderCell.Style.ForeColor  = Color.Violet;//修改列头前景字体色
//选中时不改变字体颜色
public Form1()
{
    InitializeComponent();
    //注册绑定事件
    dataGridView1.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(dgMarketInfo_CellFormatting);
}

//使其选中时不改变字体颜色
private void dgMarketInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
		e.CellStyle.SelectionForeColor = e.CellStyle.ForeColor;//不变字体色
		e.CellStyle.SelectionBackColor = e.CellStyle.BackColor;//不变背景色
}
//DataGridView导出到Excel(添加引用Net选项卡勾选Microsoft.Excel 14.0 Object Library[Microsoft.Office.Interop.Excel](通用Vs05-Vs10))
//注意添加引用Net选项卡勾选Microsoft.Office.Interop.Excel(通用Vs05-Vs10)
  private void ExportToExcel(DataGridView MyGridview, string Excel_name)
	{
		// Creating a Excel object.
		Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
		Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
		Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
		try
		{
			worksheet = workbook.ActiveSheet;

			worksheet.Name = Excel_name;

			int cellRowIndex = 1;
			int cellColumnIndex = 1;
			//Loop through each row and read value from each column.
			for (int i = 0; i <= MyGridview.Rows.Count - 2; i++)
			{
				for (int j = 0; j <= MyGridview.Columns.Count - 1; j++)
				{
					// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
					if (cellRowIndex == 1)
					{
						worksheet.Cells[cellRowIndex, cellColumnIndex] = MyGridview.Columns[j].HeaderText;
					}
					else
					{
						worksheet.Cells[cellRowIndex, cellColumnIndex] = MyGridview.Rows[i].Cells[j].Value.ToString();
					}
					cellColumnIndex += 1;
				}
				cellColumnIndex = 1;
				cellRowIndex += 1;
			}

			//Getting the location and file name of the excel to save from user.
			SaveFileDialog saveDialog = new SaveFileDialog();
			saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
			saveDialog.FilterIndex = 2;

			if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				workbook.SaveAs(saveDialog.FileName);
				MessageBox.Show("Export Successful");
			}
		}
		catch (System.Exception ex)
		{
			MessageBox.Show(ex.Message);
		}
		finally
		{
			excel.Quit();
			workbook = null;
			excel = null;
		}
	}
  //点击dataGridView加载数据行到textBox
  private void dataGridView1_MouseUp(object sender, MouseEventArgs e)
  {
      int Gindex = dataGridView1.CurrentRow.Index;//当前焦点行
      //点到空行的DBNull判断
          if (Convert.IsDBNull(dataGridView1.Rows[Gindex].Cells[0].Value) == false)
          {
              textBox1.Text = dataGridView1.Rows[Gindex].Cells[0].Value.ToString();
              textBox2.Text = dataGridView1.Rows[Gindex].Cells[4].Value.ToString();
              dateTimePicker3.Value = Convert.ToDateTime(dataGridView1.Rows[Gindex].Cells[8].Value);
          	
          }
          else
          {
          	  textBox1.Text = null;
              textBox2.Text = null;
              dateTimePicker3.Value = System.DateTime.Now;
          }
  }
//DataGridView控件固定大小
  dataGridView1.Columns[0].Visible = false;
  dataGridView1.Columns[1].Width = 38;
  dataGridView1.Columns[2].Width = 100;