Solved

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

Posted on 2016-09-16
13
54 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
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 
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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

685 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