C#让datagridview 显示行号

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;

 


namespace WindowsApplication5
{
    public partial class Form1 : Form
    {

        public const string DB_CONN_STRING =
         "data source=;initial catalog=;uid=;pwd=";
    
            SqlConnection sqlConnection1 = new SqlConnection();
            SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter();
            SqlCommand sqlSelectCommand1= new SqlCommand();
          
         public Form1()
        {
            InitializeComponent();
            this.sqlDataAdapter1.SelectCommand = this.sqlSelectCommand1;
            this.sqlSelectCommand1.CommandText = "SELECT * from ";
            this.sqlSelectCommand1.Connection = this.sqlConnection1;
        }

 

 

        private void Form1_Load(object sender, EventArgs e)
        {
            sqlConnection1.ConnectionString = DB_CONN_STRING;
            sqlConnection1.Open();
            //打开数据库连接
            DataSet objDataset;
            //新建一个放数据的DataSet
            objDataset = new DataSet();
            sqlDataAdapter1.Fill(objDataset, "address");
            //将数据填入DataSet
            this.dataGridView1.DataSource = objDataset.Tables["address"].DefaultView;
            //绑定数据
            sqlConnection1.Close();
        }
        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            //判断是不是列Header   
            if (e.ColumnIndex < 0 && e.RowIndex >= 0)
            {  
                //单元格描绘  
                e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
                //决定行号码描绘的范围   
                //不管e.AdvancedBorderStyle和e.CellStyle.Padding  
                Rectangle indexRect = e.CellBounds; indexRect.Inflate(-2, -2);
                //行号码描绘  
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), e.CellStyle.Font, indexRect, e.CellStyle.ForeColor, TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
                //描绘完后通知
                e.Handled = true;
            }
        }
    }
}

你可能感兴趣的:(datagridview)