//方法一 向每行的单元格中添加文本信息
Random rd = new Random();
for (int i = 0; i < 5; i++)
{ int index = this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[index].Cells[0].Value = "Component" + i;
float l_value1 = (float)rd.Next(100, 900) / (float)10;
this.dataGridView1.Rows[index].Cells[1].Value =
string.Format("{0:0.00}", l_value1);
this.dataGridView1.Rows[index].Cells[2].Value = "%";
this.dataGridView1.Rows.Add(row);
}
//方法二 向每行的单元格中添加控件
Random rd = new Random();
for (int i = 0; i < 5; i++)
{ DataGridViewRow row = new DataGridViewRow();
DataGridViewButtonCell dgv_btn_cell = new DataGridViewButtonCell();
dgv_btn_cell.Value = "Component" + i;
row.Cells.Add(dgv_btn_cell);
dataGridView1.Rows.Add(row);
}
DataGridViewTextBoxColumn dgv_column = new DataGridViewTextBoxColumn();
dgv_column.Name = "column_component";
dgv_column.DataPropertyName = "column_component";
dgv_column.HeaderText = "Component";
dataGridView1.Columns.Add(dgv_column);
i = int.Parse(dataGridView1.SelectedRows[0].Index.ToString());
i = dataGridView1.CurrentRow.Index;
i = dataGridView1.CurrentCell.RowIndex;
dataGridView1.RowsDefaultCellStyle.Font = new Font("宋体", 10F, FontStyle.Regular);
dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 20F, FontStyle.Regular);
DataGridView1.AllowUserToResizeColumns = False;
DataGridView1.AllowUserToResizeRows = False;
DataGridView1.Columns(0).Resizable = DataGridViewTriState.False;
DataGridView1.Rows(0).Resizable = DataGridViewTriState.False;
DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;
DataGridView1.Columns(0).MinimumWidth = 100;
DataGridView1.Rows(0).MinimumHeight = 50;
dataGridView1.RowHeadersVisible = false;
dataGridView1.AllowUserToAddRows = false;
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dataGridView1.ColumnHeadersHeight = 40;
DataGridView1.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
列冻结(当前列以及左侧做所有列)
DataGridView1.Columns(1).Frozen = True;
行冻结(当前行以及上部所有行)
DataGridView1.Rows(2).Frozen = True;
指定单元格冻结(单元格所在行上部分所有行,列左侧所有列)
DataGridView1(0, 0). Frozen = True;
DataGridViewButtonCell dgv_btn_cell = new DataGridViewButtonCell();
dgv_btn_cell.Style.BackColor = Color.DarkGray;
dgv_btn_cell.Style.ForeColor = Color.Black;
private void dataGridView1_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex != -1 && e.ColumnIndex == 1)
{
e.CellStyle.BackColor = Color.Red;
e.CellStyle.ForeColor = Color.Blue;
}
}
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Red;
dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor= Color.Blue;
DataGridViewButtonCell dgv_btn_cell = new DataGridViewButtonCell();
dgv_btn_cell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
DataGridView1.AllowUserToOrderColumns = True;
//但是如果列冻结的情况下,冻结的部分不能变更到非冻结的部分。
//变更后列位置取得
Console.WriteLine(DataGridView1.Columns("Column1").DisplayIndex);
DataGridView1.Columns("Column1").DisplayIndex = 0;
DataGridView1.MultiSelect = False; //不可以同时选择多行,单元格选择的时候默认为选择整行
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
https://www.cnblogs.com/huatao/p/4758418.html
https://blog.csdn.net/i1tws/article/details/77454110
https://blog.csdn.net/chengxuxiaoming/article/details/38518603
//行高列宽自动调整
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
//
DataGridViewRow row = new DataGridViewRow();
DataGridViewImageCell imageCell = new DataGridViewImageCell();
//从资源文件中读取图片,并且规定图片大小
imageCell.Value = new BitMap(System.Drawing.Image类型的图像, width,height);
imageCell.ImageLayout = DataGridViewImageCellLayout.Stretch;//设置图形布局,对图形进行拉伸
//将图片添加至行的单元格中
row.Cells.Add(imageCell);
//将行添加至dgv中
dataGridView1.Rows.Add(row);
这是由于在对dgv的数据源属性进行赋值后,dgv会自动刷新,使得光标更新到第一行。
如:根据以下代码,可判断:点击dgv中某一行后光标不会更新到第一行;而点击BUTTON后光标会刷新至第一行。
修改BUTTON
注意:先求i,在对设定数据源,否则i永远为0
i = dataGridView1.CurrentRow.Index;//求当前行序号
dataGridView1.DataSource = dat.Tables[0];//设置数据源
dt = dat.Tables[0];//数据集中第一个表
dr = dt.Rows[i];//表的第i行
dgv的MouseDown事件
// hittest全局变量DataGridView.HitTestInfo hittest;
hittest = dataGridView1.HitTest(e.X, e.Y);
//MessageBox.Show(hittest.ToString());
this.dataGridView1.Rows[hittest.RowIndex].Selected = true;
dgv的MouseUp事件
i = dataGridView1.CurrentRow.Index;//i为所选行的行序号
dt = dat.Tables[0];//将dat的第一张表赋给dt
dr = dt.Rows[i];//将dt的第i行赋给dr
注意:将以下代码写到最后,防止其他语句隐藏着刷新操作。
dataGridView1.FirstDisplayedScrollingRowIndex = hittest.RowIndex;
dataGridView1.Rows[hittest.RowIndex].Selected = true;
dataGridView1.Rows[0].Selected = false;
(1)、利用SqlDataAdapter对象向dgv中填充数据
//方法一
//使用DataSet绑定时,同时指明DateMember
conn = new SqlConnection("server = DESKTOP-TP0M4VK ; database = 企业人事管理系统; Trusted_Connection=yes");//连接数据库
conn.Open();//打开连接
cmd = "select ID,name,sex,birplace,polistatus,birdate,edu,idcard,nation,password from person";
adapter = new SqlDataAdapter(cmd, conn);//执行连接
DataSet Ds = new DataSet();
adapter.Fill(Ds);
this.dataGridView1.DataSource = Ds;
this.dataGridView1.DataMember = "表名";
conn.Close();//关闭连接
//方法二
//使用DataSet绑定时,直接用DataTable来绑定
DataSet Ds = new DataSet();
this.dataGridView1.DataSource = Ds.Table[0];
//this.dataGridView1.DataSource = Ds.Table["表名"];
//方法三
//直接用DataTable绑定
conn = new SqlConnection("server = DESKTOP-TP0M4VK ; database = 企业人事管理系统; Trusted_Connection=yes");//连接数据库
conn.Open();//打开连接
cmd = "select ID,name,sex,birplace,polistatus,birdate,edu,idcard,nation,password from person";
adapter = new SqlDataAdapter(cmd, conn);//执行连接
DataTable Dt = new DataTable();
adapter.Fill(Dt);
this.dataGridView1.DataSource = Dt;
conn.Close();
//方法四
//使用DataView进行绑定
conn = new SqlConnection("server = DESKTOP-TP0M4VK ; database = 企业人事管理系统; Trusted_Connection=yes");//连接数据库
conn.Open();//打开连接
cmd = "select ID,name,sex,birplace,polistatus,birdate,edu,idcard,nation,password from person";
adapter = new SqlDataAdapter(cmd, conn);//执行连接
DataView dv = new DataView();
adapter.Fill(dv.ToTable());
this.dataGridView1.DataSource = Dt;
conn.Close();
(2)、利用ArrayList对象向dgv中填充数据
//方法一
ArrayList Al = new ArrayList();
for (int i = 0; i < 10; i++)
{
list.Add(new DictionaryEntry(i.ToString(),i.ToString()+"_List"));
}
this.dataGridView1.DataSource = Al;
//方法二
ArrayList Al = new ArrayList();
Al.Add(new PersonInfo("a","-1"));
Al.Add(new PersonInfo("b","-2"));
Al.Add(new PersonInfo("c","-3"));
this.dataGridView1.DataSource = Al;
(3)、利用Dictionary
Dictionary<string, string> dic = new Dictionary<string, string>();
for (int i = 0; i < 10; i++)
{
dic.Add(i.ToString(),i.ToString()+" ");
}
this.dataGridView1.DataSource = dic;
例:
private void Form1_Load(object sender, EventArgs e)
{
//使用Dictionary<>泛型集合填充DataGridView
Dictionary<String, Student> students = new Dictionary<String, Student>();
Student hat = new Student("Hathaway", "12", "Male");
Student peter = new Student("Peter","14","Male");
Student dell = new Student("Dell","16","Male");
Student anne = new Student("Anne","19","Female");
students.Add(hat.StuName,hat);
students.Add(peter.StuName,peter);
students.Add(dell.StuName,dell);
students.Add(anne.StuName,anne);
//在这里必须创建一个BindIngSource对象,用该对象接收Dictionary<>泛型集合的对象
BindingSource bs = new BindingSource();
//将泛型集合对象的值赋给BindingSourc对象的数据源
bs.DataSource = students.Values;
this.dataGridView1.DataSource = bs;
}
(4)、利用List 泛型对象向dgv中填充数据
this.dataGridVi.DataSource = new BindingList<Object>(List<Object>);
例:
private void Form1_Load(object sender, EventArgs e)
{
//使用List<>泛型集合填充DataGridView
List<Student> students = new List<Student>();
Student hat = new Student("Hathaway", "12", "Male");
Student peter = new Student("Peter","14","Male");
Student dell = new Student("Dell","16","Male");
Student anne = new Student("Anne","19","Female");
students.Add(hat);
students.Add(peter);
students.Add(dell);
students.Add(anne);
this.dataGridView1.DataSource = students;
}
(5)、利用SqlDataReader对象向dgv中填充数据
SqlCommand command = new SqlCommand("select * from tablename", conn)
SqlDataReader dr = command.ExecuteReader();
BindingSource bs = new BindingSource();
bs.DataSource = dr;
this.dataGridView1.DataSource = bs;
在进行数据源绑定之后,DataGridView列的字段名称与数据库中的列字段名称一致,修改方法为:
dataGridView1.Columns[filedName].HeaderText = name;
//首先将绑定的数据源强制转化为数据表DataTable
DataTable dt = ((DataView)(this.dgvFenxzgl.DataSource)).Table.DataSet.Tables[0];
//获得表中被修改的数据
DataTable dtModified = dt.GetChanges(DataRowState.Modified);
if (dtModified.Rows.Count > 0)//如果行数大于0.表示已经有数据被修改了
{
//在这里我们可以获得被修改的数据
//获得被修改的数据
foreach (DataRow item in dtModified.Rows)
{
//根据表结构获得它每行每列的值
/*
* item["MEIKMC"].ToString();
* ...
*/
}
}
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
KryptonMessageBox.Show(e.Exception.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
e.Cancel = true;
}
CellBeginEdit事件----CellParsing事件----CellEndEdit事件
注意:CellParsing事件中以下两句代码非常重要
e.Value = e.Value.ToString().ToUpper();//必须是通过e.Value来获得重新输入的值,如果是通过this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()这种方法获得,那么获得值将是原来的值,并不是用户刚刚输入的值;同时该语句也正可以对用户输入的数据进行验证,如果不符合则将原来的值再赋给该单元格,不进行修改
e.ParsingApplied = true;//必须将e.ParsingApplied属性设置为true,否则刚刚用户输入的值不会更新,还是会将原来的值赋给该单元格
绑定数据后,为了使用户能在这里添加数据,DataGridView控件下面会默认添加以*打头的一条新行。若希望在绑定后不显示该行,及不可以在DataGridView中直接添加行,而只能通过按钮的形式进行添加。
this.dataGridView1.AllowUserToAddRows=false;
这也是dataGridView1.Rows.Count总是比数据行数大一的原因
此外,dataGridView1.Rows.Count会随着dataGridView1.DataSource = dat.Tables[0];语句的执行而变化。变化规律我暂时没发现,等之后补充。欢迎大佬指点,感激不尽!