Как показать серийный номер.в представлении сетки данных в формах окон C # - PullRequest
0 голосов
/ 02 января 2012

У меня есть вид сетки данных, и я установил для него свойство источника данных
а

dgvEmployee.DataSource = mycollection;

я хочу, чтобы сетка имела какое-то свойство, например

dgvEmployee.ShowSerialNumber = True;

Любое предложение

Заранее спасибо

Ответы [ 7 ]

3 голосов
/ 02 января 2012

Этот фрагмент кода взят из здесь

    /// This class extends the the DataGridView so row numbers will 
    /// automatically appear in the row header cells. In this 
    /// implementation, the width of the column that contains the row 
    /// header cells is automatically adjusted to accomodate the row 
    /// numbering.
    /// ******************************************************************
    ///  AUTHOR: Daniel S. Soper
    ///     URL: http://www.danielsoper.com
    ///    DATE: 20 February 2007
    /// LICENSE: Public Domain. Enjoy!   :-)
    /// ******************************************************************
    /// 
    class MyDGV : DataGridView
    {
        public MyDGV()
        {
            //perform any necessary customization initialization here
        } //end default constructor

        protected override void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e)
        { //this method overrides the DataGridView's RowPostPaint event 
          //in order to automatically draw numbers on the row header cells
          //and to automatically adjust the width of the column containing
          //the row header cells so that it can accommodate the new row
          //numbers,

            //store a string representation of the row number in 'strRowNumber'
            string strRowNumber = (e.RowIndex + 1).ToString();

            //prepend leading zeros to the string if necessary to improve
            //appearance. For example, if there are ten rows in the grid,
            //row seven will be numbered as "07" instead of "7". Similarly, if 
            //there are 100 rows in the grid, row seven will be numbered as "007".
            while (strRowNumber.Length < this.RowCount.ToString().Length) strRowNumber = "0" + strRowNumber;

            //determine the display size of the row number string using
            //the DataGridView's current font.
            SizeF size = e.Graphics.MeasureString(strRowNumber, this.Font);

            //adjust the width of the column that contains the row header cells 
            //if necessary
            if (this.RowHeadersWidth < (int)(size.Width + 20)) this.RowHeadersWidth = (int)(size.Width + 20);

            //this brush will be used to draw the row number string on the
            //row header cell using the system's current ControlText color
            Brush b = SystemBrushes.ControlText;

            //draw the row number string on the current row header cell using
            //the brush defined above and the DataGridView's default font
            e.Graphics.DrawString(strRowNumber, this.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - size.Height) / 2));

            //call the base object's OnRowPostPaint method
            base.OnRowPostPaint(e);
        } //end OnRowPostPaint method
    } //end class
1 голос
/ 25 декабря 2013
//1-add new column to  dataGridView1 call it ser or your Name
//2-set it's DataPropertyName To None "Very Important"
//3-Set HeaderText to ("Your Name To shown In Header")
//4-Set frozen To True 
//5-in DefultCellStyle Do Thise
//  A-Set BackColor To AnyColor you Want
//  b-Set Null Value to 0 or 1 as you prefer
//  b-Set Alignment To middleCenter
//6- call Method MakeSerieal() everyTime You Want To fill dataGridView1
//7- call Method MakeSerieal() In ColumnHeaderMouseClick ("It help if you Want To Reorder dataGridView1")

//--------------------------
private void MakeSerieal()
{

  if (dataGridView1.Rows.Count > 1)
                        {
                            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
                            {
                                dataGridView1.Rows[i].Cells[0].Value = (i + 1).ToString();
                            }
                        }
}
//--------------------------

//With My Regards 
//Ahmed Mansour ("Egypt")
//Mansour_VbKing@Yahoo>com
0 голосов
/ 08 августа 2017

Это похоже на то, что кому-то нужно добавить серийные номера в их таблицу данных, и вы хотите, чтобы серийные номера действовали как маркеры и цифры в слове Microsoft: - вот ответ. Вы можете вызвать этот метод в свойствах datagridview "RowsAdded" и "RowsRemoved"

//improvised answer of  ahmed mansour 

private void MakeSerieal()
{
   if (dataGridView1.Rows.Count > 0)
    {
       int slno = 0;
       for (int i = 0; i < dataGridView1.Rows.Count; i++)
         { 
           slno= slno+1;
           dataGridView1.Rows[i].Cells[0].Value = slno.ToString();
         }
    }
 }
0 голосов
/ 11 апреля 2014

Попробуйте это Определенно работает:

            SqlDataAdapter sda0 = new SqlDataAdapter(sqlCmd0);
            DataTable Dt0 = new DataTable();
            Dt0.Columns.Add("SlNo");
            Dt0.Columns["SlNo"].AutoIncrement = true;
            Dt0.Columns["SlNo"].AutoIncrementSeed = 1;
            sda0.Fill(Dt0);
            grdName.DataSource = Dt0;
0 голосов
/ 02 января 2012

Попробуйте это ... Не уверен, но попробуйте это.

Заполните таблицу данных из базы данных и добавьте новый столбец в таблицу данных

 DataColumn dcAuto = new DataColumn();
  dcAuto.AutoIncrement = true;
  dcAuto.AutoIncrementSeed = 1;
  dt.Columns.Add(dcAuto);

Привязка данных к представлению таблицы.

0 голосов
/ 02 января 2012

Подклассы сетки и добавить ее.

class MyGrid : DataGridView
{
    public bool ShowSerialNumber
    {
         get ...
         set ...
    }
}
0 голосов
/ 02 января 2012

Добавить новое поле шаблона в сетку данных,

внутри поля шаблона добавьте метку ..

в событии привязки строки к сетке данных установите текст метки в серийный номер. http://bytes.com/topic/c-sharp/answers/874915-how-generate-serial-number-datagrid-view-automatically

...