c#datagridview

//保证显示当前活动单元格
this.Invoke(new Action(() =>
{
 dataGridView1.CurrentCell = dataGridView1.Rows[index].Cells[0]; 
}));
//添加新行
index=dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[
0].Value = (index+1).ToString();//添加内容 dataGridView1.Rows[index].Cells[1].Value = ip;//添加内容 dataGridView1.Rows[index].Cells[2].Value = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"); //添加内容
 //表头自动序号
private void dataGridView1_RowPostPaint_1(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush b = new SolidBrush(this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor);
            e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), this.dataGridView1.DefaultCellStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 4);

        }
        /// <summary>
        /// datagridview清除排序列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 清除排序列表ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
                column.SortMode = DataGridViewColumnSortMode.Automatic;
            } 
        }

 

        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                //鼠标右键弹出菜单
                if (e.Button == MouseButtons.Right)
                {
                    if (e.RowIndex >= 0)
                    {
                        //若行已是选中状态就不再进行设置
                        if (dataGridView1.Rows[e.RowIndex].Selected == false)
                        {
                            dataGridView1.ClearSelection();
                            dataGridView1.Rows[e.RowIndex].Selected = true;
                        }
                        //只选中一行时设置活动单元格
                        if (dataGridView1.SelectedRows.Count == 1)
                        {
                            dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                        }
                        //弹出操作菜单
                        contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
                    }
                }
            }
            catch
            {

            }

        }

 

你可能感兴趣的:(c#datagridview)