Solved

Adding a Row to a DataGridView with a string that contains all the parameters

Posted on 2016-09-16
13
49 Views
Last Modified: 2016-09-20
strRowData is a string variable that contains all the parameters for the Add method.  It's value is "22,1,0,1,0,1,1,1", but the statement "DataGridView1.Rows.Add(strRowData)" tries to set the first column to "22,1,0,1,0,1,1,1" rather than the first column to "22", the second column to "1", etc.  How can I run the statement given that one string contains all the parameters?  Is there a way to run dynamic code in vb.net?
0
Comment
Question by:Declan_Basile
  • 8
  • 4
13 Comments
 
LVL 12

Assisted Solution

by:funwithdotnet
funwithdotnet earned 250 total points
ID: 41802465
Create a new row, split the string, add the appropriate value to each column and then add the row.
0
 
LVL 63

Accepted Solution

by:
Fernando Soto earned 250 total points
ID: 41802562
Hi  Declan_Basile;

You need to use an Object array in order to load a row of data that way. The following code snippet will do that
'' Your data
Dim strRowData = "22,1,0,1,0,1,1,1"
'' Convert your data string into an array
Dim strRowDataArray As Object() = strRowData.Split(New Char() {","c})
'' Add the array as a row in the DataGridView
dataGridView1.Rows.Add(strRowDataArray)

Open in new window

Be aware that adding rows to the DatedGridView in this manner requires that you do NOT have a bound data source to the DatedGridView control. Also you need to make sure that you have added the correct number of columns using code as the following
'' The number of columns in the DataGridView
dataGridView1.ColumnCount = 8
dataGridView1.Columns(x).Name = "Column Name"
'' Where x is the column index"

Open in new window

0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41805441
I already have an array of Long Integers.  In fact, I created strRowData from it, but DataGridView1.Rows.Add(LongIntArray) doesn't work.  It looks like it needs to be an array of objects, not an array of Long Integers.  I've experimented further, and this works:

Dim x(7) As Object        
x(0) = 22
DataGridView1.Rows.Add(x(0), 0)

But this doesn't ...

Dim x(7) As Object        
x(0) = Clng(22)
DataGridView1.Rows.Add(x(0), 0)

How can I convert the array of long integers to an array of objects?
0
How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

 
LVL 63

Expert Comment

by:Fernando Soto
ID: 41805486
Please post all code that you are using to  instantiate the DataGridView and initialize it as well as your code that you are using to load rows of data.
0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41805524
    Private Sub AddDataGridRows()

        Dim cn As New SqlConnection(strConn)
        Dim cmd As New SqlCommand
        Dim rdr As SqlDataReader
        Dim lngUserId As Long
        Dim OpIds((DataGridView1.ColumnCount - 1)) As Long
        Dim Vals((DataGridView1.ColumnCount - 1)) As Long
        Dim i As Integer

        For i = 0 To OpIds.GetUpperBound(0)
            OpIds(i) = DataGridView1.Columns(i).Tag
        Next

        cn.Open()
        cmd.CommandText = "procUserOperations"
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Connection = cn
        cmd.Parameters.Add("@ParentOperationId", SqlDbType.Int)
        cmd.Parameters("@ParentOperationId").Value =
            IIf(IsDBNull(cbxParentOperationId.SelectedValue), "0", cbxParentOperationId.SelectedValue)
        rdr = cmd.ExecuteReader

        DataGridView1.Rows.Clear()
        lngUserId = 0
        Do While rdr.Read
            If rdr("UserId") <> lngUserId Then
                If lngUserId <> 0 Then
                    Vals(0) = lngUserId
                    Call AddDataGridRow(Vals)
                    Array.Clear(OpIds, 0, OpIds.GetUpperBound(0))
                End If
                lngUserId = rdr("UserId")
            End If
            Vals(Array.IndexOf(OpIds, CLng(rdr("OperationId")))) =
                 IIf(rdr("ChildOps") = rdr("UserChildOps"), 2, 1)
        Loop
        If lngUserId <> 0 Then
            Vals(0) = lngUserId
            Call AddDataGridRow(Vals)
        End If

        'DataGridView1(1, 0).Style.BackColor = Color.LightGray
        'DataGridView1(2, 0).Style.BackColor = Color.Yellow

    End Sub

    Private Sub AddDataGridRow(ByRef Vals() As Long)

        'Dim i As Integer
        'Dim strRowData As String

        'strRowData = Vals(0).ToString
        'For i = 1 To Vals.GetUpperBound(0)
        'strRowData = strRowData & IIf(Vals(i) = 0, ", 0", ", -1")
        'Next

        DataGridView1.Rows.Add(Vals)

    End Sub

Open in new window

0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 41805685
In order to do this
For i = 0 To OpIds.GetUpperBound(0)
    OpIds(i) = DataGridView1.Columns(i).Tag
Next

Open in new window

You needed to add Columns to the DataGridView. If you created the DataGridView with the Form designer please open the file FormName.Designer.vb and copy the section of code inside the subroutine called Private Sub InitializeComponent() and the section marked as 'DataGridView1. Also post any other code that you have that initialize it such as adding columns. I am trying to build a test project with what you have so I can test the code you are using.
0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41806569
I do have code to add the columns.
   Private Sub RefreshMatrix()

        Dim SQL As String
        Dim cn As New ADODB.Connection()
        cn.ConnectionString = strConn2
        cn.Open()

        SQL = "Select DISTINCT O.OperationId, O.Operation, " &
            "IIf(R2.ParentOperationId Is NULL, 0, 1) As IsParent " &
            "FROM (Operations O INNER JOIN RelOperationOperation R " &
            "On O.OperationId = R.ChildOperationId) LEFT JOIN RelOperationOperation R2 On " &
            "R.ChildOperationId = R2.ParentOperationId WHERE R.ParentOperationId = " &
            IIf(IsDBNull(cbxParentOperationId.SelectedValue), "0", cbxParentOperationId.SelectedValue.ToString) &
            " ORDER BY O.Operation"

        Dim rs As New ADODB.Recordset()
        rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient
        rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic
        rs.LockType = ADODB.LockTypeEnum.adLockReadOnly
        rs.Open(SQL, cn)
        rs.ActiveConnection = Nothing
        cn.Close()

        DataGridView1.Columns.Clear()
        AddDataGridCbxColumn()
        rs.MoveFirst()
        Do While Not rs.EOF
            AddDataGridColumn(rs.Fields("OperationId").Value.ToString, rs.Fields("Operation").Value,
                              rs.Fields("IsParent").Value)
            rs.MoveNext()
        Loop
        AddDataGridRows()
        'Dim da As New System.Data.OleDb.OleDbDataAdapter()
        'Dim ds As New DataSet()
        'da.Fill(ds, rs, "products")
        'DataGridView1.Columns.Clear()

    End Sub

Open in new window

0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41806574
I'm going to try adding in a blank row and then assigning the values to the cells.
0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41806612
This code works ...
    Private Sub AddDataGridRow(ByRef Vals() As Long)

        DataGridView1.Rows.Add()
        DataGridView1.Rows(DataGridView1.RowCount - 2).Cells(0).Value = 22
        'Note the header row counts as a row, hence RowCount - 2

    End Sub

This code does not work

    Private Sub AddDataGridRow(ByRef Vals() As Long)

        DataGridView1.Rows.Add()
        DataGridView1.Rows(DataGridView1.RowCount - 2).Cells(0).Value = Vals(0)

    End Sub

Why doesn't the second version work?  I even displayed the value of Vals(0) to confirm the value using the statement "MsgBox(Vals(0))" and it displayed "22".
0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41806664
Note Column(0) of DataGridView1 is a combobox column bound to a datasource and its ValueMember is bound to a column of the datasource that's a long integer.
0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 41806725
Please do the following. Create a test project with one DataGridView control and use the code that works and does not work from two post back because I am confused on what you're trying to achieve.

Thanks
0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41807089
I declared the vals array as Int32 instead of Long and it worked!
0
 
LVL 1

Author Closing Comment

by:Declan_Basile
ID: 41807686
Thank you!
0

Featured Post

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question