none
how to insert row number on a datagridview RRS feed

  • Question

  • how to insert auto increment row number of every row on a datagridview

    for example:

    record_number          id          name

    1                               1           christian

    2                               1           christian

    3                               2            jake


    Saturday, February 16, 2019 6:41 AM

Answers

  • Hi no[one]

    Have you asked the same question before?
    Putting that aside, please use this code.

    ' --- you have already ---
    For i As Long = 1 To days
        dgv1.Rows.Add(label_id.Text, Label5.Text, Label4.Text, picker1.Value.AddMonths(CInt(i)).ToString("MM/dd/yyyy"))
    Next
    
    ' --- set sequantial nuber in column 0 -----------------
    Dim rowSeq as Integer = 0	' -- or as Long = 0
    For myRow as integer = 0 to dgv1.Rows.Count - 1
        dgv1(0, myRow).Value = myRow + 1
    Next
    ' --------------------
    

     Regards,


    Ashidacchi -- https://ssl01.rocketnet.jp/hokusosha.com/default.html

    • Marked as answer by no[one] Monday, February 18, 2019 9:00 AM
    Saturday, February 16, 2019 11:58 PM

All replies

  • Hi no[one],

    There are two ways to show sequential row number on a DataGridView.
    (a) insert a new column at the left, and set seq number in it.
    (b) use RowHeader (so-called "Record Selector") on a DataGridView, and set seq number in it.

    I always use (b). And how-to is...(1) make RowHeader visible (in default)  
    (2) after storing data in all rows (or after binding data), make a loop from 0 to the last row

    Here is a sample code of (2)
    With DataGridView1
    	' --- set incremental/sequential number in HeaderCell
    	For rowNum As Integer = 0 To .Rows.Count - 1
    	    .Rows(rowNum).HeaderCell.Value = (rowNum + 1).ToString
    	Next
    	' --- optional: auto adjust width of RowHeader and make string centering ---
    	.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
    	.RowHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
    End With
    


    Regards,

    Ashidacchi -- https://ssl01.rocketnet.jp/hokusosha.com/default.html

    Saturday, February 16, 2019 9:44 AM
  • Here is a custom DataGridView that does row numbers. Add to your project, compile then it will appear at the top of the IDE toolbox.

    Public Class DataGridViewRowNumber
        Inherits DataGridView
    
        Protected Overrides Sub OnRowPostPaint(e As DataGridViewRowPostPaintEventArgs)
            Dim rowNumber As String = (e.RowIndex + 1).ToString()
    
            Dim sizeVar As SizeF = e.Graphics.MeasureString(rowNumber, Font)
            If RowHeadersWidth < CInt(sizeVar.Width + 20) Then
                RowHeadersWidth = CInt(sizeVar.Width + 20)
            End If
    
            Dim b As Brush = SystemBrushes.ControlText
    
            e.Graphics.DrawString(rowNumber, Font, b, e.RowBounds.Location.X + 15,
                                  e.RowBounds.Location.Y + ((e.RowBounds.Height - sizeVar.Height) / 2))
    
            MyBase.OnRowPostPaint(e)
    
        End Sub
    End Class


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Saturday, February 16, 2019 10:52 AM
    Moderator
  • Thank you for your reply but how to do it with a header name?
    Saturday, February 16, 2019 11:20 AM
  • Thank you for your reply but how to do it with a header name?
    Never saw a reason to go that and it's a special cell dedicated to selecting all rows and cells in the DataGridView. So with that I have nothing to offer.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Saturday, February 16, 2019 11:39 AM
    Moderator
  • sorry but can you save the row selector in sql database?

    pls help me

    Saturday, February 16, 2019 12:28 PM
  • DataGridView is a kind of view, not data itself.
    We cannot save the row selector in any database.

    Ashidacchi -- https://ssl01.rocketnet.jp/hokusosha.com/default.html

    Saturday, February 16, 2019 12:59 PM
  • thats why im asking the one that have a header name

    im just a beginner

    Saturday, February 16, 2019 1:02 PM
  • how to fill up the first column in the picture?

    here is my code in the picture

     Dim date2 As Date = d2
            Dim date1 As Date = d1

            Dim days As Long = DateDiff(DateInterval.Month, picker1.Value, picker2.Value.AddMinutes(1))
            dgv1.Rows.Add(label_id.Text, Label5.Text, lbl_partial.Text, picker1.Value.ToString("MM/dd/yyyy"))

            For i As Long = 1 To days
                dgv1.Rows.Add(label_id.Text, Label5.Text, Label4.Text, picker1.Value.AddMonths(CInt(i)).ToString("MM/dd/yyyy"))
            Next

    what i want to do is to  insert auto increment number of every row on a datagridview

    Saturday, February 16, 2019 2:25 PM
  • Create a DataTable as shown below

    Dim dt As New DataTable
    dt.Columns.Add(
        New DataColumn() With
            {
                      .ColumnName = "RecordNumber",
                      .DataType = GetType(Integer),
                      .AutoIncrement = True,
                      .AutoIncrementSeed = 1
            })
    

    Then using the same DataTable load data from the database table e.g.

    dt.Load(cmd.ExecuteReader)

    where cmd is your command object with a valid connection open.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Saturday, February 16, 2019 2:35 PM
    Moderator
  • Why, AdoNet is not handling in that way. 

    AdoNet is an disconnected provider. So in a program it gives by default only rownumbers likewise -1 and further down. 

    At the moment of an update it looks at the real current rownumbers. In an environment of 1000 of users there can be endless ones adding rows. 

    At that moment you do an update it assigns the real rownumbers. 

    Therfore again "Why". Forget that AdoNet is created for 1970 kind of application. It assumes that more persons are using a database. 


    Success
    Cor

    Saturday, February 16, 2019 9:17 PM
  • Hi no[one]

    Have you asked the same question before?
    Putting that aside, please use this code.

    ' --- you have already ---
    For i As Long = 1 To days
        dgv1.Rows.Add(label_id.Text, Label5.Text, Label4.Text, picker1.Value.AddMonths(CInt(i)).ToString("MM/dd/yyyy"))
    Next
    
    ' --- set sequantial nuber in column 0 -----------------
    Dim rowSeq as Integer = 0	' -- or as Long = 0
    For myRow as integer = 0 to dgv1.Rows.Count - 1
        dgv1(0, myRow).Value = myRow + 1
    Next
    ' --------------------
    

     Regards,


    Ashidacchi -- https://ssl01.rocketnet.jp/hokusosha.com/default.html

    • Marked as answer by no[one] Monday, February 18, 2019 9:00 AM
    Saturday, February 16, 2019 11:58 PM
  • Hi

    Form Code:

    private SqlDbConnect con;
            int ID = 0;
            public FrmDept()
            {
                InitializeComponent();
            }

    private void btnAdd_Click(object sender, EventArgs e)
            {
                if (txtDescrption.Text != "")
                {
                    con = new SqlDbConnect();
                    con.SqlQuery("INSERT INTO Tbl_Department (Description) VALUES (@Description)");
                    con.Cmd.Parameters.AddWithValue("@Description", txtDescrption.Text.Trim());
                    //con.SqlQuery("INSERT INTO Tbl_Dest (Description) VALUES (@Description)");
                    //con.Cmd.Parameters.AddWithValue("@Description", txtDescrption.Text.Trim());
                   
                    con.NonQueryEx();
                    txtDescrption.Text = "";
                    FillDataGrid();
                }else
                {
                    MessageBox.Show("No Data");
                    txtDescrption.Focus();
                }
            }
            private void FillDataGrid()
            {
                {
                    con = new SqlDbConnect();
                    
                    con.SqlQuery("SELECT Id ,Description as 'Dept' FROM Tbl_Department");
                   
                    dGV.DataSource = con.QueryEx();
                    dGV.Columns[0].Visible = false;
                    Gcount();
                   
                   
                }
            }
        //Fill Record Number S/N
             private void Gcount()
             {
                for (int i = 0; i < dGV.Rows.Count; i++)
                {
                    DataGridViewRowHeaderCell cell = dGV.Rows[i].HeaderCell;
                    cell.Value = (i + 1).ToString();
                    dGV.Rows[i].HeaderCell = cell;
                }
             }

    ----Data Base Classe

    public class SqlDbConnect
        {
            private SqlConnection _con;
            public SqlCommand Cmd;
            private SqlDataAdapter _da;
            private DataTable _dt;
            public SqlDbConnect()
            {
               
                _con = new SqlConnection(@"Data Source=serverName;Initial Catalog=DataBaseName;User ID=sa;Password=???????");
                _con.Open();
            }
            public void SqlQuery(string queryText)
            {
                Cmd = new SqlCommand(queryText, _con);
            }
            public DataTable QueryEx()
            {
                _da = new SqlDataAdapter(Cmd);
                _dt = new DataTable();
                _da.Fill(_dt);
                return _dt;
            }
            public void NonQueryEx()
            {
                Cmd.ExecuteNonQuery();
            }
        }

    Please click the Mark as answer button and vote as helpful if this reply solves your problem.

    Best Regards.


    Sunday, February 17, 2019 1:15 AM